Dictionaries in Swift

This post is a deep dive into Dictionaries in Swift, we will discuss the structure as well as the utility of dictionaries in programming.

A dictionary is basically another collection data type, similar to arrays dictionaries also hold multiple variables. If you are new to collection data types, you may want to check out Arrays in Swift.

Structure of a dictionary

In Swift, a dictionary variable is created similar to an array, but instead of simply putting in a list of variables, dictionaries are created using the key-value pair. The key is the variable that can be used by us, whereas the value is the actual primitive value assigned to the key.

Take a real-life dictionary, for example, to find the meaning of a word you first locate the word and then read the definition. Dictionaries in Swift are similar, the actual word is the key whereas the definition of that word is its value. Here’s how it will look in code:

import SwiftUI 

var dictionary = ["Photosynthesis": "the process by which green plants use sunlight and water to make food and oxygen"]

To create a dictionary, simple use [] brackets, and have the key, in this case, the word “photosynthesis”, followed by “:” and then the value, which is the definition. You are not limited to a single entry, you can include multiple pairs within your dictionary like:

import SwiftUI

var dictionary = ["Photosynthesis" : "the process by which green plants use sunlight and water to make food and oxygen" ,
                  "Chlrophyll" : "a green pigment used in plants for photosynthesis" , 
                  "Tranpiriation" : "the exhalation of water vapor through the stomata"]
print(dictionary)
Output: 

["Photosynthesis" : "the process by which green plants use sunlight and water to make food and oxygen" , 
"Chlrophyll" : "a green pigment used in plants for photosynthesis" , 
"Tranpiriation" : "the exhalation of water vapor through the stomata"]

It is important that you separate the key-value pairs with a “,” other it will cause a syntax error. It is also crucial to know that, unlike arrays, the keys in a dictionary are immutable, meaning that they cannot be changed.

Adding elements to a dictionary

To add elements to a Swift dictionary, use the name of the dictionary followed by the [] like:

var playerAges = ["Ronaldo": 37, "Messi": 34]
print("First Dictionary: ",playerAges)
playerAges["Neymar"] = 30
print("New Dictionary: ",playerAges)
Output: 

First Dictionary: ["Ronaldo": 37, "Messi": 34]
New Dictionary: ["Ronaldo": 37, "Messi": 34, "Neymar": 30]

By using this, we have added a new element to our dictionary, the key being “Neymar”, and since this dictionary holds soccer players’ names the value is 30.

Changing values in a dictionary

By accessing the particular key of a dictionary, we can also modify its value. This can be done using:

var lastName = [1: "Singh", 2: "Kumar", 3: "Das"]
print("First Dictionary: ", lastName)
lastName[2] = "Kapoor"
print("New Dictionary: ", lastName)
First Dictionary:  [1: "Singh", 2: "Kumar", 3: "Das"]
New Dictionary:  [1: "Singh", 2: "Kapoor", 3: "Das"]

Here, we have changed the value at key 2, which is assigned to the String “Kumar”, and executing this function we replace this value with “Kapoor”, as shown in the output.

Access values from a dictionary

In Swift, we can extrapolate the keys and the values independently, and use them as necessary. We can access the keys in a dictionary using the key property of a dictionary:

var capitals = ["Romania":"Bucharest", "India":"Delhi", "Indonesia":"Jakarta"]
print("Dictionary: ", capitals)
var countryName  = Array(capitals.keys)
print("Keys: ", countryName)
Output

Dictionary:  ["India": "Delhi", "Romania": "Bucharest", "Indonesia": "Jakarta"]
Keys:  ["India", "Romania", "Indonesia"]

Similarly, we can access the values in a dictionary using the value property of a dictionary:

var capitals = ["Romania":"Bucharest", "India":"Delhi", "Indonesia":"Jakarta"] 
print("Dictionary: ", capitals) 
var capitalName = Array(capitals.values) 
print("Values: ", capitalName)
Output

Dictionary:  ["India": "Delhi", "Romania": "Bucharest", "Indonesia": "Jakarta"]
Values:  ["Delhi", "Bucharest", "Jakarta"]

Removing values from a dictionary

To remove a value from a Dictionary, we can use the .removeValue() method:

var companies = ["Apple": "Tim Cook", "Tesla": "Elon Musk", "Google": "Sundar Pichai"]
print("First Dictionary: ", companies)
var removedValue  = companies.removeValue(forKey: "Tesla")
print("New Dictionary: ", companies)
Output

First Dictionary:  ["Apple": "Tim Cook", "Tesla": "Elon Musk", "Google": "Sundar Pichai"]
New Dictionary:  ["Apple": "Tim Cook", "Google": "Sundar Pichai"]

Here, .removeValue() method locates and deletes both the element and the value associated with the key. 

Find the number of elements in a dictionary

We can use the count property to find the number of elements in a dictionary by:

var names = ["Name1": "Vivek", "Name2": "Mikhail", "Name3": "Saad", "Name4": "Mukesh"]
print(names.count)
Output

4

Since the names dictionary had four elements, the code above prints 4.

Leave a Reply

Your email address will not be published.