Dictionary in Swift


In this tutorial, you will learn about dictionaries. You will learn what is a dictionary and how to create it in Swift programming.

You will also understand how to access, add elements, remove elements and many other things that you can do in Swift dictionary.

What is a Dictionary in Swift?

A dictionary is a collection type that is used to store a collection of information as key-value pairs that can be accessed in the program.

Dictionaries are unordered because the key-value items of a dictionary do not have a default order or sorting.

Just like an array, a dictionary also stores the same type of items.

Below is an example of a dictionary where we have 5 cities of America by population:

// Create a dictionary of top 5 American cities by population
var citiesByPopulation = [
    "New York": 8804190,
    "Los Angeles": 3898747,
    "Chicago": 2746388,
    "Houston": 2304580,
    "Phoenix": 1608139
]

print(citiesByPopulation)

In the above example, the keys of the dictionary represent the name of cities and the values represent the number of populations.

We can represent the above dictionary as a table as you can see below:

Cities (Keys)Population (Values)
New York8804190
Los Angeles3898747
Chicago2746388
Houston2304580
Phoenix1608139
Representation of keys and values of the dictionary as table

In our example, the keys are string type and the values are integer type. The type of the above dictionary is [String: Int]. This is because the keys are string type and values are integer type.

Creating a dictionary in Swift

Let’s see how a dictionary can be created…

Creating an empty dictionary

At the very first, let’s see the syntax for creating an empty dictionary:

var dictionaryName = [KeyType: ValueType]()

Below is an example of creating a dictionary with the key type string and the value is integer type:

var myDictionary = [String: Int]()

Now see another example of creating an [Int: String] type dictionary:

var myDictionary = [Int: String]()

Creating a dictionary with given values

Below is the syntax for creating a dictionary with already given keys and values:

var dictionaryName:[KeyType:ValueType] = [.........]

Now let’s see with an example by creating a dictionary with given values:

var weatherData:[String:Int] = [
    "Temperature": 27,
    "Humidity": 91,
    "Wind Speed": 23,
]

print(weatherData)

The output will be:

["Temperature": 27, "Humidity": 91, "Wind Speed": 23]

Swift can automatically set the type of key and value of a dictionary even if we have not set it just like variables. Below is the same dictionary we have created but have not set the type:

var weatherData = [
    "Temperature": 27,
    "Humidity": 91,
    "Wind Speed": 23,
]

print(weatherData)

And it gives the same output as the previous one. it automatically assigns the dictionary type as [String:Int] because the keys are string type and values are integer type.

Adding, removing and updating of items to a dictionary

Both adding, removing and updating items to a dictionary is quite an easy task. But you have to keep in mind that you have to store the dictionary in a variable, not in a constant. This is because, variables are mutable, but constants are immutable literate in Swift.

Also, the dictionary type collection is unordered, so don’t expect it to be in order and your added item may not be the last item. Even your added item becomes the last one, then also it will be by luck.

Adding item

We can easily add an item to a dictionary using [] after the dictionary name.

Below is an example of adding an item to a dictionary:

var weatherData = [
    "Temperature": 27,
    "Humidity": 91,
    "Wind Speed": 23,
]

weatherData["Rain Probability"] = 71
print(weatherData)

The output of the above program is:

["Temperature": 27, "Humidity": 91, "Wind Speed": 23, "Rain Probability": 71]

Removing item from dictionary

Removing an item is also as simple as adding an item to a dictionary. Here we have just set the value nil to the existing key.

Below is an example of removing an item:

var weatherData = [
    "Temperature": 27,
    "Humidity": 91,
    "Wind Speed": 23,
]

weatherData["Temperature"] = nil
print(weatherData)

And the output will be something like you can see below:

["Humidity": 91, "Wind Speed": 23]

We can also remove an element using the removeValue method:

var studentsMarks = [
    "John": 57,
    "Sasuke": 87,
    "Jennifer": 73,
]

studentsMarks.removeValue(forKey: "Sasuke")
print(studentsMarks)

Output:

[“John”: 57, “Jennifer”: 73]

To remove all the elements, we can use the removeAll() method:

studentsMarks.removeAll()

Updating an item

Updating the value of a key is very similar to removing an element from a dictionary. The only difference is that here you are not setting the value to nil.

Below is the example of updating the value of a key in the dictionary:

var studentData = [
    "Age": 15,
    "score": 87,
    "Room No": 7,
]

studentData["Age"] = 16
print(studentData)

Output:

["Room No": 7, "Age": 16, "score": 87]

You can see in the output, that the key age changed to 16 from 15.

Access dictionary element

Now let’s see how we can access dictionary elements…

Accessing dictionary value by key

We can access the value of an element from a dictionary using its key. Below is the example:

var studentData = [
    "Age": 15,
    "score": 87,
    "Room No": 7,
]

var studentAge = studentData["Age"]
print("Age is: \(studentAge!)")

And the output will be:

Age is: 15

Access dictionary values only

Using the values property, you can access all the values in the dictionary. Below is the example:

var studentsMarks = [
    "John": 57,
    "Sasuke": 87,
    "Jennifer": 73,
]

var marks = Array(studentsMarks.values)
print(marks)

The output will be:

[87, 57, 73]

In the above example, we have created an array and the elements of the generated array are the values of the keys from the dictionary.

Iterate or looping over a dictionary

We can use both for loop and forEach loop to iterate or loop over a dictionary to list its items.

Let’s first see how to do it using the for loop:

var studentsMarks = [
    "Emma": 68,
    "Henry": 49,
    "Sophia": 80,
]

for (student,mark) in studentsMarks {
    print("\(student): \(mark)")
}

Output:

Emma: 68
Henry: 49
Sophia: 80

We can do the same using forEach method also.

Below is the example to loop through a dictionary using the Swift forEach method:

var studentsMarks = [
    "Emma": 68,
    "Henry": 49,
    "Sophia": 80,
]

studentsMarks.forEach { item in
    print("\(item.key): \(item.value)")
}

Finding the number of dictionary items

it is a quite simple task to get the number of elements in a Swift dictionary. To count the total number of items Swift provides the count property.

Below is the example to find the number of dictionary elements:

var studentName = [
    64: "Henry",
    98: "Lucas",
    123: "Isabella"
]

var numberOfElements = studentName.count
print(numberOfElements)

Output:

3

That’s it for now. There are some other dictionary methods also available to perform specific tasks.

Also, read: