Collections and functions

Swift Dictionaries

An introduction to dictionaries in Swift: how to create key-value pairs, read and change values by key, add and remove entries, and use count and isEmpty.

This tutorial belongs to the Swift series

A dictionary is a collection of key-value pairs. You look values up by key, the way you look words up in a paper dictionary.

Here’s a dictionary with 2 pairs, where each key is a String and each value is an Int:

var dict = ["Roger": 8, "Syd": 7]

Swift infers the type as [String: Int]. You can also write it yourself:

var dict: [String: Int] = ["Roger": 8, "Syd": 7]

For an empty dictionary you must give the type, because there’s nothing to infer from. Here we create an empty dictionary with String keys and Int values:

var dict = [String: Int]()

// or

var dict: [String: Int] = [:]

Reading values

You read a value by putting the key in square brackets:

var dict = ["Roger": 8, "Syd": 7]

dict["Roger"] // 8
dict["Syd"]   // 7

Here’s the detail that trips people up: the result is not an Int. It’s an Int?, an optional. The key might not be in the dictionary, and Swift has to give you something in that case:

dict["Tina"] // nil

So you unwrap it, like any other optional:

if let age = dict["Roger"] {
    print("Roger is \(age)")
}

Or you give a default value for missing keys:

dict["Tina", default: 0] // 0

Changing and adding values

Assigning to a key changes its value:

dict["Roger"] = 9

A dictionary must be declared with var to be modified. If you declare it with let, you can’t add, change, or remove entries.

The same syntax adds a new pair when the key isn’t there yet:

dict["Tina"] = 4

Removing values

To remove a pair, assign nil to the key:

dict["Tina"] = nil

Or call removeValue(forKey:):

dict.removeValue(forKey: "Tina")

Both do the same thing. removeValue(forKey:) also returns the removed value, which is handy when you want to use it one last time.

Counting

count gives you the number of pairs:

var dict = ["Roger": 8, "Syd": 7]
dict.count // 2

isEmpty is true when there are none:

var dict = [String: Int]()
dict.isEmpty // true

There are many more methods, but these are the basics you’ll use daily.

Copies and iteration

Dictionaries are value types. Pass one to a function or return it, and Swift copies it. Changes to the copy don’t affect the original.

Dictionaries are collections, so you can loop over them with for-in and get a (key, value) tuple on each pass. Remember that a dictionary has no defined order, so don’t expect the pairs to come out in the order you inserted them.

Lesson completed