Learning Swift
上QQ阅读APP看书,第一时间看更新

Swift's type system

Swift is a strongly typed language, which means that every constant and variable is defined with a specific type. Only values of a matching type can be assigned to them. So far, we have been taking advantage of a feature of Swift called type inference. This makes it such that the code does not have to explicitly declare a type if it can be inferred from the value assigned to it during declaration.

Without the type inference, the name variable declaration from before would be written as:

var name: String = "Sarah"

This code explicitly declares name as the type String with the value "Sarah". A constant or variable's type can be specified by adding a colon (:) and a type after its name.

A String type is defined by a series of characters. This is perfect for storing text like our name example. The reason that we don't actually need to specify the type is that "Sarah" is a String literal. The text surrounded by quotation marks is a String literal and is inferred to be of the type String. This means that the name it can infer must be of the type String if you make its initial value "Sarah".

Similarly, if we did not use type inference for our other variable declarations, they would look like this:

let pi: Double = 3.14

var invitees: [String] = ["Sarah", "Jamison", "Roana"]

let showsByGenre: [String:String] = [
    "Comedy": "Modern Family",
    "Drama": "Breaking Bad",
    "Variety": "The Colbert Report",
]

Double is a number type that can store decimal numbers. An array's type is declared by putting the type of element it stores within square brackets. Finally, a dictionary's type is defined in the form [KeyType:ValueType]. All of these types can be inferred because each of them is assigned to a value that has an inferable type.

This code is much cleaner and easier to understand if we leave the types out, as the original examples showed. Just keep in mind that these types are always implied to be there, even if they are not written explicitly. If we tried to assign a number to the name variable, we would get an error as:

Swift's type system

Here, we are trying to assign a number, specifically an Int type, to a variable that was inferred to be of a String type. Swift will not allow that.

Especially when dealing with inferred types, it can be extremely useful to ask Xcode what type a variable is inferred to be. You can do this by holding the option key on your keyboard and by clicking on the variable name. This will display a popup that looks like this:

Swift's type system

As expected, the variable was indeed inferred to be of the type String.

Types are an integral part of Swift. They are one of the major reasons that Swift is so safe as a programming language. They help the compiler know more about your code and because of that, the compiler can automatically warn you about bugs without even running your code.