CODEX

Swift Dictionaries

Learn what is a dictionary and how to use it

Artturi Jalli
CodeX
Published in
3 min readFeb 26, 2021

--

Photo by Pisit Heng on Unsplash

Swift Dictionaries

Swift dictionaries are the basic building blocks of your code. A dictionary is a container for storing key-value pairs. A key acts as a unique identifier for the value.

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

How to Create a Dictionary in Swift

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].

How to Access a Dictionary Value in Swift

A dictionary value is accessed via a subscript.

For example, let’s get the player number of Ronaldo:

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

How to Update a Value of a Dictionary in Swift

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

--

--

Artturi Jalli
CodeX
Writer for

Check @jalliartturi on YouTube to become a successful blogger. (For collabs, reach me out at: artturi@bloggersgoto.com)