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 matching types can be assigned to them. So far, we have taken advantage of a feature of Swift called Type Inference. This means that the code does not have to explicitly declare a type if it can be inferred from the value being assigned to it during the declaration.

Without Type Inference, the name variable declaration from before would be written as follows:

var name: String = "Sarah"

This code is explicitly declaring 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 is defined by a series of characters. This is perfect for storing text, as in our name example. The reason that we don't need to specify the type is that Sarah is a string literal. Text surrounded by quotation marks is a string literal and can be inferred to be of the type String. That means that name must be of the type String if you make its initial value Sarah.

Similarly, if we had not used 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",
]

Double is a numeric type that can store decimal numbers. An array's type is declared by putting the type of element it stores in 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.

The 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 shown:

Swift's type system

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

When dealing with inferred types, it is extremely useful to ask Xcode what type a variable is inferred to be. You can do this by holding down the Option key on your keyboard and clicking on the variable name. This will display a pop-up that looks like this:

Swift's type system

As was 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 learn more about your code and, because of that, the compiler can warn you about bugs automatically without even running your code.

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

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