Dictionaries

In Swift, a dictionary is a container for storing key-value pairs.

In layman’s terms, you can use a dictionary to store unique items that are related to some values.

For instance, let’s create a dictionary that maps a student ID to the name of the student:

let data = [324982: "Alice", 318902: "Bob", 410922: "Charlie"]

In this chapter, you learn how to use dictionaries in Swift.

This chapter is part of a completely free Swift for Beginners guide. Make sure you have completed all the chapters from the start before reading this one.

Disclaimer: To learn Swift, you have to repeat everything you see in this guide and in the following guides. If you only read the guides, you are not going to learn anything!

Dictionaries in Swift

In Swift, you can store related data in a dictionary as key-value pairs.

The idea of a dictionary is that for each unique key, there is a related value.

This value can be accessed by knowing the key.

For instance, a university could store student data as a student ID -> student name dictionary. If you know the ID, you can get the name of the student.

A dictionary key must be unique.

In other words, there can be no two equal keys. However, the values do not need to be unique.

In the student example, it does not make sense for two students to have the same student ID. But having the same name is no problem because the students are still characterized by a unique ID.

In the next section, you are going to learn how to create a dictionary in Swift.

How to Create a Dictionary

To create a dictionary, use square brackets similar to how you create an array.

However, this time, each element is a key-value pair. In other words, a key followed by a colon and the value.

[key1: value1, key2: value2, ... , keyN: valueN]

For example, let’s create a dictionary that represents student ID: student name data:

let data = [324982: "Alice", 318902: "Bob", 410922: "Charlie"]

What Is the Data Type of a Dictionary?

Similar to arrays, the data type of a dictionary is denoted with [] by specifying the data types of the keys and values as separated by a colon.

[keyType: valueType]

For instance, the data type of the student ID: student name dictionary is [Int: String] because each key is an integer and each value is a string.

You can explicitly specify this as follows:

let data: [Int:String] = [324982: "Alice", 318902: "Bob", 410922: "Charlie"]

In this case, specifying the data type is not mandatory as it is clear from the context.

However, more often than not, you should be explicit about the types of data you use to avoid confusion and improve code readability!

If you want to create an empty dictionary, you have to specify its data type. This is because Swift needs to know what type of data the dictionary is going to have in the future.

Also, to create an empty dictionary, you need to add a colon in between the square brackets:

let data: [Int:String] = [:]

Next, you are going to learn how to access the values of a dictionary.

How to Access an Element of a Dictionary

The main benefit of a dictionary is you can access a value as long as you know its key.

To access the value of a specific key, use the square brackets operator by giving it the key as a parameter.

Here is the general syntax:

dictionary[keyName]

For instance, let’s access the player who has the jersey number 7 in a player data dictionary:

let playerData = [
    7: "Ronaldo",
    10: "Messi",
    9: "Bale"
]

let player1 = playerData[7]

print(player1)

Output:

Optional("Ronaldo")

As you can see, the result is wrapped inside an optional.

This is clever because the key you tried to access is not guaranteed to be found in the dictionary.

If there is no value for a key, nil is returned instead.

And as you recall, something that can either be a value or nil is represented with optionals in Swift.

If you want to get the value without being wrapped inside an optional, you need to unwrap the optional.

In this case, you can use optional binding.

Let’s repeat the above example.

This time, let’s unwrap the optional player name using optional binding:

let playerData = [
    7: "Ronaldo",
    10: "Messi",
    9: "Bale"
]

if let player1 = playerData[7] {
    print(player1)
}

Output:

Ronaldo

As promised in the optionals chapter earlier, you are going to deal with optionals a lot. Accessing dictionary values is one common example of using optionals in your code.

Now you can create and read dictionaries in Swift.

Next, you are going to learn how to add, remove, and update key-value pairs.

How to Add an Element to a Dictionary

To add an element to a dictionary in Swift, you need to “access” a non-existent key and assign a value to it.

dictionary[newKey] = newValue

This piece of code adds a new key called newKey and sets its value to newValue.

For example, let’s add a new player with the jersey 8 to the data and then print the whole dictionary:

var playerData = [
    7: "Ronaldo",
    10: "Messi",
    9: "Bale"
]

playerData[8] = "Gerrard"

print(playerData)

Output:

[7: "Ronaldo", 10: "Messi", 9: "Bale", 8: "Gerrard"]

As you can see, now there is a new key-value pair in the mix.

How to Update an Element in a Dictionary

Updating a key-value pair happens exactly the same way as adding a new one.

Use the square bracket accessing operator with a specific key and assign an updated value to it.

dictionary[someKey] = updatedValue

This updates the value for a key called someKey by assigning a new value called updatedValue to it.

Notice that if no such key exists, a new key-value pair is created!

For example, given a data dictionary of soccer players and their numbers let’s update the player with number 7:

var playerData = [
    7: "Ronaldo",
    10: "Messi",
    9: "Bale"
]

playerData[7] = "Beckham"

print(playerData)

Output:

[9: "Bale", 10: "Messi", 7: "Beckham"]

As you can see, “Ronaldo” was swapped with “Beckham”.

How to Remove an Element from a Dictionary

To remove a key-value pair from a dictionary, use the dictionary’s built-in removeValue() method.

This method works such that it:

  1. Takes a key as an argument.
  2. Checks if there is such a key in the dictionary.
  3. Removes the key-value pair.
  4. Returns the removed value as an optional value.

For instance, let’s remove the player number 9:

var playerData = [
    7: "Ronaldo",
    10: "Messi",
    9: "Bale"
]

playerData.removeValue(forKey: 9)

print(playerData)

Output:

[10: "Messi", 7: "Ronaldo"]

Because this method returns the removed value, you could store it into a variable or constant if you need to.

For example:

var playerData = [
    7: "Ronaldo",
    10: "Messi",
    9: "Bale"
]

// Store the removed value into a constant
let removedValue = playerData.removeValue(forKey: 9)

print("Removed", removedValue)
print(playerData)

Output:

Removed Optional("Bale")
[7: "Ronaldo", 10: "Messi"]

As you can see, this piece of code both removed the value for key 9 as well as store the value into a constant.

Now you understand the basics of dictionaries in Swift. You can create dictionaries and add, remove, and update key-value pairs in them.

Next, let’s talk about looping through dictionaries.

How to Loop Through a Dictionary

Similar to arrays, a dictionary can consist of thousands of entries.

More often than not, you want to go through each of these elements to perform some action on them.

Going through the elements manually would make no sense.

Instead, you should use a loop to iterate over a dictionary.

A conventional way to iterate over a dictionary is by using a for loop.

For Loop Syntax

To iterate over a dictionary with a for loop, you need to store both the key and the value to temporary constants during each iteration.

for (key, value) in dictionary {
    // actions
}

This for loop goes through the dictionary entry by entry.

It stores each key and each value to constants called key and value respectively. You can access these constants inside the loop inside the curly brackets.

For instance, let’s loop through a dictionary of soccer player data and print out each key and value:

var playerData = [
    7: "Ronaldo",
    10: "Messi",
    9: "Bale"
]

for (number, name) in playerData {
    print(number, name)
}

Output:

10 Messi
9 Bale
7 Ronaldo

Next, let’s talk about how to get all the keys from a dictionary in Swift.

How to Get Dictionary Keys in Swift

When dealing with dictionaries, sometimes you want to access all the keys without caring about the values.

To do this, you can use the keys property of a dictionary.

dictionary.keys

This method returns an array that consists of all the keys in the dictionary.

For example, let’s get all the player numbers (keys) from the following dictionary:

var playerData = [
    7: "Ronaldo",
    10: "Messi",
    9: "Bale"
]

let keys = playerData.keys
print(keys)

Output:

[7, 10, 9]

Similar to how you can access the keys of a dictionary, you can also access its values.

How to Get Dictionary Values in Swift

To get all the values of a dictionary, access the values property of a dictionary.

dictionary.values

This gives you an array that only consists of the values of a dictionary.

For example, let’s get the player names (values) from the following dictionary:

var playerData = [
    7: "Ronaldo",
    10: "Messi",
    9: "Bale"
]

let values = playerData.values
print(values)

Output:

["Bale", "Ronaldo", "Messi"]

Example: Array to Dictionary

Write a function that:

  1. Takes an array of integers as an input.
  2. Returns a dictionary that maps each number in the input array to its square.

Please, try this yourself before looking at the solution below.

To solve this problem, the function needs to

  1. Take an array of numbers as an argument.
  2. Specify a return type of dictionary that maps an integer to an integer.
  3. Initialize an empty result dictionary for storing the numbers and their squares.
  4. Loop through the numbers in the argument array.
  5. Insert each number as a key to the dictionary and assign the number squared as its value.
  6. Return the result.

Here is how it looks in code:

func squarify(numbers: [Int]) -> [Int: Int] {
    var squareData: [Int: Int] = [:]
    for number in numbers {
        squareData[number] = number * number
    }
    return squareData
}

// Example call
let squareData = squarify(numbers: [1, 2, 3])
print(squareData)

Output:

[1: 1, 3: 9, 2: 4]

Notice how the order of the result looks odd. This is not a mistake. Due to performance, dictionary does not have an ordering, so the key-value pairs appear randomly when printed out this way.

This concludes the chapter as well as the whole course!

Congratulations!

What an amazing accomplishment if you made it this far.

Congrats!

Now you have a solid understanding of the basics of Swift programming language.

With these basic-level programming skills, you now are ready to start learning how to build iOS apps.

However, this is just a small step in becoming the next top-notch developer.

If you want to get some perspective, feel free to read an article about how long it really takes to learn programming. To put it short, it can take between 500-and 1000 hours to learn programming at a job-ready level!

If you practice 8 hours a day, you can become a professional iOS developer in less than 6 months at best!

Remember to practice a lot. Ask a lot of questions. Watch many tutorials!

As the next steps, you should start searching for some iOS development tutorials on the internet and start building real iOS apps.

You can give me feedback about this course by shooting an email at [email protected].