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 z is a Boolean, based on their initial values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset