How to access values in a Swift Dictionary

Swift has its own dictionaries, much like Objective-C has the NSDictionary class. Although the two are bridged, they are not the same: trusty old NSDictionary methods do not work with Swift Dictionaries.

Here’s a quick summary of how Swift Dictionaries work.

Creating and iterating over Swift Dictionaries

Let’s create a Swift Dictionary and then list all its values using Fast Enumeration:

// make a Swift Dictionary (Option 1)
var dict: Dictionary = ["key1": "Value 1", "key2": "Value 2", "key3": "Value 3"]

// or, specifying the key/value types (Option 2)
var dict: [String: String] = ["key1": "Value 1", "key2": "Value 2", "key3": "Value 3"]

// or, specifying nothing at all and let everything be inferred (Option 3)
var dict = ["key1": "Value 1", "key2": "Value 2", "key3": "Value 3"]

// list all values
for (key, value) in dict {
    print(key, value)
}

// output: 
key1 Value 1
key3 Value 3
key2 Value 2

The easiest way to create a dictionary is Option 3, letting the compiler infer everything. The other two options are valid too.

What’s special in comparison to NSDictionaries is that in Swift, we can pass both the key and the value to the for loop, rather than just the key.

Accessing a single key’s value

What the elaborate Apple documentation doesn’t explicitly mention for stupid people like me is how to access a single value in the Swift Dictionary. It’s surprisingly simple:

// list a single key's value
print("Value for key1 is", dict["key1"])

// output
Value for key1 is Value 1

Changing a value in our dictionary

We can use the same syntax to update a value in our Swift Dictionary too. Notice that the dictionary must be declared as a variable rather than a constant. The compiler is nice enough to offer this service free of charge:

// change the value of key1 to something else
dict["key1"] = "New Value"
print("Value for key1 is now", dict["key1"])

// output
Value for key1 is now New Value

Adding key/value pairs to our dictionary

To add another key/value pair, we’ll pretend it already exists and simply set its value:

// add a key/value pair 
dict["key4"] = "Brand New Item"

Counting all entries in the dictionary

To see how many key/value pairs we have in our dictionary, we can call the count method:

// how large is the array?
print("The dictionary has", dict.count, "entries.")

// output
The dictionary has 3 entries.

Clearing out a Swift Dictionary

To empty the whole dictionary from all keys and values without destroying the whole thing, we can use this:

// empty my dictionary
dict = [:]
print("The dictionary now has", dict.count, "entries.")

// output
The dictionary has 0 entries.

This is different to setting the dictionary to nil because it leaves the key/value types in place (here: String and String).

Further Reading





Leave a Reply