O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Type inference

Type inference allows us to omit the variable type when we define it. The compiler will infer the type based on the initial value. For example, in Objective-C we would define an integer like this:

  int myInt = 1 

This tells the compiler that the myInt variable is of the int type, and the initial value is the number 1. In Swift, we would define the same integer like this:

  var myInt = 1 

Swift infers that the variable type is an integer because the initial value is an integer. Let's look at a couple more examples:

var x = 3.14  // Double type  
var y = "Hello"  // String type  
var z = true  // Boolean type 

In the preceding example, the compiler will correctly infer that variable x is a Double, variable, y is a String, and variable ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required