Buy the PDF

Chapter 7 Dictionaries

Similar to Arrays, Dictionaries in Swift are typed. You need to specify the type of both the keys and the values when you declare the dictionary. Once initialized, your dictionary can only contain key-value pairs that match that type signature.

Also, similar to arrays, you can declare the type signature for the dictionary explicitly or Swift can infer it from the initial values.

Let’s take a look at how you do some common operations on dictionaries in Swift.

Listing 7.1: Dictionaries.
 1 var pets = ["Polly" : "dog", "Joey" : "goldfish"]
 2 pets.count        // 2
 4 pets["Polly"]    // {Some "dog"}
 6 pets["Joey"]    //  {Some "goldfish"}
 8 pets["Joey"]!  // "goldfish"
10 var ages:Dictionary<String, Int> = Dictionary()
12 ages["Joey"] = 3
13 ages["Polly"] = 7
15 ages // ["Polly": 7, "Joey": 3]
17 for key in ages.keys {
18     print(key)
19 }
21 for val in ages.values {
22     print(val)
23 }
25 for (key, val) in pets {
26     print("\(key) the \(val) is \(ages[key]!) years old")
27 }
29 ages["Joey"] = 4
30 ages  // ["Polly": 7, "Joey": 4]
31 ages.removeValueForKey("Joey")
32 ages // ["Polly": 7]

Figure 7.1 shows the basic usage of dictionaries in Swift. We declare a dictionary by giving a list of paired values, where each pair is separated by a colon (line 1). We can then access the individual elements by key, as shown in lines 4, 6, 8. In this case the type of our dictionary is inferred from the initial assignments. In this example Swift will infer that the dictionary has a type of <String, String>, i.e. strings as keys and strings as values.

Line 10 shows how to initialize an empty dictionary. In this case we use the Dictionary() constructor, and we explicitly set the type as <String, Int>. This means that our dictionary will use strings for keys and integers as values. Once we’ve initialized the dictionary we can add values to it as shown in lines 12 and 13.

One thing to note about dictionaries in Swift is that when you access an item in a dictionary, you get an optional back. Optionals are Swift’s way of representing values that may be present or may be null. So for example, with a dictionary, we don’t know that a key will be present when we try to access a key in a dictionary. So instead of definitely returning the value, Swift returns an optional value. When you run the above code in a playground, you’ll see {Some "dog"} and {Some "goldfish"} when lines 4 and 6 are evaluated. This is because these values are optionals. If we know that a value is definitely present for something that returns an optional, we can unwrap it by adding a ! to the method call. This returns the value instead of the optional (line 8). Coming from other languages, optionals can be tricky to fully grok. But we’ll get into them in more detail in chapter 10.

The count method gives us the number of items in the dictionary (line 2).

Lines 17-27 show how we can loop through the keys and values of a dictionary. We can use the keys method with a for loop to go through the keys of a dictionary (17-19). Similarly we can use the values method of a dictionary with a for loop to go through the values of a dictionaries (21-23). Or we can just use a for loop to go through both keys and value of each item in the dictionary.

Finally we can use the removeValueForKey method to remove an element from a dictionary. Line 31 removes element with key “Joey” from the dictionary.