CODEX

Swift—Working with Dictionaries

Quickly learn what a dictionary is and how to use it by following some simple examples.

Artturi Jalli
Feb 26 · 3 min read
Photo by Pisit Heng on Unsplash

Dictionaries in Swift

In Swift, a dictionary is a container for storing key-value pairs. A key acts as a unique identifier for the value.

Create a New Dictionary

Throughout this guide, you will be working with a dictionary of footballers that relates a player to a player number. So, without further ado, let’s create a dictionary of footballers:

var footballers: [String: Int] = [
"Ronaldo": 7,
"Messi": 10
]

In this dictionary, a key is the name of the player (a string) and the value is the number of that player (an integer). Thus the type [String: Int].

Hint: If you happen to need an empty dictionary, you can create one by:

var footballers: [String: Int] = [:]

Access a Specific Value of a Dictionary

A dictionary value is accessed via a subscript. For example, to get the player number of Ronaldo, just call:

let num = footballers["Ronaldo"]print(num) // prints Optional(7)

As you can see, Ronaldo’s number is now wrapped inside an optional. This is because if you try to look up a non-existent value in the dictionary, it returns nil. (Try it yourself by replacing "Ronaldo" with e.g. "Lampard".)

Update a Value of a Dictionary

You can update a value in a dictionary in one of the two possible ways

  • Use the subscript syntax.
  • Use updateValue method

For example, change Ronaldo’s number to 9 in these two ways:

// Subscript syntax
footballers["Ronaldo"] = 9
// OR// updateValue method
footballers.updateValue(9, forKey:"Ronaldo")

The difference between these approaches is that the latter one returns the original value as it updates the new value. Thus, you can store the original value (as an optional of course) if you need to:

let originalNumber = footballers.updateValue(9, forKey:"Ronaldo")// Now originalNumber is Optional(7) and the new player number is 9

Add a New Key-Value Pair to a Dictionary

You can add a new key-value pair to the dictionary, also by:

  • Using the subscript syntax
  • Using the updateValue

For example, you can add a player called Bale to the dictionary by either:

// using the subscript syntax
footballers["Bale"] = 9
// or// using updateValue method
footballers.updateValue(9, forKey: "Bale")

Remove a Key-Value Pair from a Dictionary

Very similar to adding a new key-value pair, removing an existing one is achieved by:

  • Using subscript syntax
  • Using the removeValue method

For example, you can remove Bale from the dictionary in two ways by either:

// using the subscript syntax
footballers["Bale"] = nil
// or// using the updateValue method
footballers.removeValue(forKey: "Bale")

The difference between the subscript syntax and using removeValue is that the latter returns the (optional) value it just removed from the dictionary so that you can store it if you need to:

let baleNum = footballers.removeValue(forKey: "Bale")
print(baleNum) // Prints Optional(9)

Length of the Dictionary

In order to count the number of key-value pairs in a dictionary, you can use count method.

For example, you can count the number of footballers in the dictionary simply by:

footballers.count

To check if a dictionary is empty, you could compare count with 0. But you can just as well use isEmpty:

footballers.isEmpty // returns false if non-empty and true if empty

Loop Through a Dictionary

You can use e.g. for loop to loop through a dictionary.

For example, you can print the players and their numbers with formatted sentences by looping through the footballers dictionary:

for (player, number) in footballers {
print("\(player) has number \(number).")
}
// "Ronaldo has number 7"
// "Messi has number 10"

Get a List of Keys of the Dictionary

Get a list that only contains all the keys of a dictionary by using the keys property.

For example, get all the names of the footballers by:

let names = footballers.keys 
print(names) // prints e.g. ["Ronaldo", "Messi"]

Get a List of Values of the Dictionary

Get a list that only contains all the values of a dictionary, you can use values property.

For example, get a list of numbers of the footballers by:

let numbers = footballers.values 
print(numbers) // prints e.g. [7, 10]

CodeX

Everything connected with Tech & Code

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store