Swift Fundamentals

Dictionaries

Swift Fundamentals
1 Playgrounds 04:22
2 Variables, Constants, and Types 05:38
3 Arrays and Sets 08:08
4 Dictionaries 03:28
5 Optionals 04:41
6 Working With Optionals 08:53
7 Tuples 06:29
8 Conditionals 07:39

Another important collection type defined by the Swift standard library is the dictionary type. Dictionaries are better known as maps, hashes, or associative arrays in other programming languages. The idea is similar, though.

Dictionaries

What Are They

Dictionaries store an unordered collection of key-value pairs. The key type of a dictionary must conform to the Hashable protocol because the dictionary needs to be able to uniquely identify each key it stores.

Even though dictionaries are quite different from sets and arrays, there are some similarities. Like sets, dictionaries are unordered and, like arrays, a dictionary can contain duplicate values. The keys of a dictionary are unique, though.

Initialization

You can instantiate a dictionary one of several ways. In this example, we define a dictionary, stocks, using an initializer. We append a pair of parentheses to the shorthand form of the dictionary's type, [String: Double].

var stocks = [String: Double]()

While this is equivalent to the following example, I'm sure you agree that the shorthand form is more readable and more concise.

var stocks = Dictionary<String, Double>()

We can also use a dictionary literal to create a dictionary. The key-value pairs are wrapped in a pair of square brackets and separated by commas. The key and value of each pair are separated by a colon.

var stocks = ["AAPL": 178.46, "GOOG": 1137.51, "TSLA": 350.02]

The compiler infers the type of the dictionary by inspecting the types of the keys and values of the dictionary literal. The dictionary in the example is of type [String: Double], a dictionary with keys of type String and values of type Double.

Working With Dictionaries

Because we're already familiar with sets and arrays, working with dictionaries isn't complicated. We can ask the dictionary for the number of key-value pairs it stores by inspecting the value of its count property. A dictionary also defines an isEmpty property.

var stocks = ["AAPL": 178.46, "GOOG": 1137.51, "TSLA": 350.02]

stocks.count // 3
stocks.isEmpty // false

You can also access the keys and values of a dictionary through its keys and values properties.

var stocks = ["AAPL": 178.46, "GOOG": 1137.51, "TSLA": 350.02]

stocks.keys
stocks.values

We have several options to work with the key-value pairs stored in a dictionary. The most common and convenient option is subscript syntax.

var stocks = ["AAPL": 178.46, "GOOG": 1137.51, "TSLA": 350.02]

stocks["TWTR"] = 23.66 // add key-value pair
stocks["AAPL"] // read value for key
stocks["GOOG"] = 2150.87 // update value for key
stocks["TSLA"] = nil // remove key-value pair

But dictionaries also define a few other methods for manipulating the key-value pairs they store. The updateValue(_:forKey:) method adds or updates the value of a particular key. If the specified key doesn't exist, the key-value pair is added. If the specified key does exist, the corresponding value is updated.

var stocks = ["AAPL": 178.46, "GOOG": 1137.51, "TSLA": 350.02]

stocks.updateValue(23.66, forKey: "TWTR") // add key-value pair
stocks.updateValue(2150.87, forKey: "GOOG") // update value for key

The updateValue(_:forKey:) method has a subtle advantage over subscript syntax. It returns the old value for the specified key. If you add a new key-value pair, the method returns nil.

Dictionaries also define a method for removing key-value pairs, removeValue(forKey:), and a method to remove every key-value pair of the dictionary, removeAll().

var stocks = ["AAPL": 178.46, "GOOG": 1137.51, "TSLA": 350.02]

stocks.removeValue(forKey: "GOOG")

stocks.removeAll()

Iterating over the contents of a dictionary is similar to iterating over the values of an array or set. The difference is that a tuple is returned for every key-value pair of the dictionary. We discuss tuples later in Swift Fundamentals.

var stocks = ["AAPL": 178.46, "GOOG": 1137.51, "TSLA": 350.02]

for (key, value) in stocks {
    print("\(key): \(value)")
}

What's Next?

As a Swift developer, arrays, sets, and dictionaries are constructs you use every day. They're lightweight and easy to use, but powerful and versatile.

Next Episode "Optionals"

Stop Writing Swift That Sucks

Download the Swift Patterns I Swear By