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

Core Swift types

Every programming language needs to name a piece of information so that it can be referenced later. This is the fundamental way in which code remains readable after it is written. Swift provides a number of core types that help you represent your information in a very comprehensible way.

Constants and variables

Swift provides two types of information: a constant and a variable:

// Constant
let pi = 3.14

// Variable
var name = "Sarah"

All constants are defined using the let keyword followed by a name, and all variables are defined using the var keyword. Both constants and variables in Swift must contain a value before they are used. This means that, when you define a new one, you will most likely give it an initial value. You do so by using the assignment operator (=) followed by a value.

The only difference between the two is that a constant can never be changed, whereas a variable can be. In the preceding example, the code defines a constant called pi that stores the information 3.14 and a variable called name that stores the information "Sarah". It makes sense to make pi a constant because pi will always be 3.14. However, we need to change the value of name in the future so we defined it as a variable.

One of the hardest parts of managing a program is the state of all the variables. As a programmer, it is often impossible to calculate all the different possible values a variable might have, even in relatively small programs. Since variables can often be changed by distant, seemingly unrelated code, more states will cause more bugs that are harder to track down. It is always best to default to using constants until you run into a practical scenario in which you need to modify the value of the information.

Containers

It is often helpful to give a name to more complex information. We often have to deal with a collection of related information or a series of similar information like lists. Swift provides three main collection types called tuples, arrays, and dictionaries.

Tuples

A tuple is a fixed sized collection of two or more pieces of information. For example, a card in a deck of playing cards has three properties: color, suit, and value. We could use three separate variables to fully describe a card, but it would be better to express it in one:

var card = (color: "Red", suit: "Hearts", value: 7)

Each piece of information consists of a name and a value separated by a colon (:) and each is separated by a comma (,). Finally, the whole thing is surrounded by parentheses (()).

Each part of a tuple can be accessed separately by name using a period (.), otherwise referred to as a dot:

card.color // "Red"
card.suit // "Hearts"
card.value // 7

You are also able to create a tuple with no names for each part of it. You can then access them based on where they are in the list, starting with zero as the first element:

var diceRoll = (4, 6)
diceRoll.0 // 4
diceRoll.1 // 6

Another way to access specific values in a tuple is to capture each of them in a separate variable:

let (first, second) = diceRoll
first // 4
second // 6

If you want to change a value in a tuple, you can assign every value at once or you can update a single value, using the same reference as in the preceding code:

diceRoll = (4, 5)
diceRoll.0 = 2
Arrays

An array is essentially a list of information of variable length. For example, we could create a list of people we want to invite to a party, as follows:

var invitees = ["Sarah", "Jamison", "Marcos", "Roana"]

An array always starts and ends with a square bracket and each element is separated by a comma. You can even declare an empty array with open and closing brackets: [].

You can then add values to an array by adding another array to it, like this:

invitees += ["Kai", "Naya"]

Note that += is the shorthand for the following:

invitees = invitees + ["Kai", "Naya"]

You can access values in an array based on their position, usually referred to as their index, as shown:

invitees[2] // Marcos

The index is specified using square brackets ([]) immediately after the name of the array. Indexes start at 0 and go up from there like tuples. So, in the preceding example, index 2 returned the third element in the array, Marcos. There is additional information you can retrieve about an array, like the number of elements that you can see as we move forward.

Dictionaries

A dictionary is a collection of keys and values. Keys are used to store and look up specific values in the container. This container type is named after a word dictionary in which you can look up the definition of a word. In that real life example, the word would be the key and the definition would be the value. As an example, we can define a dictionary of television shows organized by their genre:

var showsByGenre = [
   "Comedy": "Modern Family",
   "Drama": "Breaking Bad",
]

A dictionary looks similar to an array but each key and value is separated by a colon (:). Note that Swift is pretty forgiving with how whitespace is used. The array could be defined with each element on its own line and the dictionary could be defined with every element on a single line. It is up to you to use whitespace to make your code as readable as possible.

With the dictionary defined as shown above, you would get the value Modern Family if you looked up the key Comedy. You access a value in code similar to how you would in an array but, instead of providing an index in the square brackets, you provide the key:

showsByGenre["Comedy"] // Modern Family

You can define an empty dictionary in a similar way to an empty array but with a dictionary you must also include a colon between the brackets: [:].

Adding a value to a dictionary is similar to retrieving a value but you use the assignment operator (=):

showsByGenre["Variety"] = "The Colbert Report"

As a bonus, this can also be used to change the value for an existing key.

You might have noticed that all of my variable and constant names begin with a lower case letter and each subsequent word starts with a capital letter. This is called camel case and it is the widely accepted way of writing variable and constant names. Following this convention makes it easier for other programmers to understand your code.

Now that we know about Swift's basic containers, let's explore what they are in a little more detail.