Swift Programming

Swift Dictionary

In this tutorial, we’ll learn everything about Swift dictionaries; how they are created, accessing, adding, removing elements from them, and various built-in methods.

Swift dictionary is an unordered collection of items. It stores elements in key/value pairs. Here, keys are unique identifiers that are associated with each value.

Let’s see an example.

If we want to store information about countries and their capitals, we can create a dictionary with country names as keys and capitals as values.

Keys Values
Nepal Kathmandu
Italy Rome
England London

Create a dictionary in Swift

Here’s how we can create a dictionary in Swift.

var capitalCity = ["Nepal": "Kathmandu", "Italy": "Rome", "England": "London"]
print(capitalCity)

Output

["Nepal": "Kathmandu", "England": "London", "Italy": "Rome"]

In the above example, we have created a dictionary named capitalCity. Here,

  • Keys are "Nepal""Italy""England"
  • Values are "Kathmandu""Rome""London"

When we run this code, we might get output in a different order. This is because the dictionary has no particular order.

Note: Here, keys and values both are of String type. We can also have keys and values of different data types.


Example: Swift Dictionary

// dictionary with keys and values of different data types
var numbers = [1: "One", 2: "Two", 3: "Three"]
print(numbers)

Output

[3: "Three", 1: "One", 2: "Two"]

In the above example, we have created a dictionary named numbers. Here, keys are of Int type and values are of String type.


Add Elements to a Dictionary

We can add elements to a dictionary using the name of the dictionary with []. For example,

var capitalCity = ["Nepal": "Kathmandu", "England": "London"]
print("Initial Dictionary: ",capitalCity)

capitalCity["Japan"] = "Tokyo"

print("Updated Dictionary: ",capitalCity)
print(capitalCity["Japan"])

Output

Initial Dictionary:  ["Nepal": "Kathmandu", "England": "London"]
Updated Dictionary:  ["Nepal": "Kathmandu", "England": "London", "Japan": "Tokyo"]

In the above example, we have created a dictionary named capitalCity. Notice the line,

capitalCity["Japan"] = "Tokyo"

Here, we have added a new element to capitalCity with keyJapan and valueTokyo.


Change Value of Dictionary

We can also use [] to change the value associated with a particular key. For example,

var studentID = [111: "Eric", 112: "Kyle", 113: "Butters"]
print("Initial Dictionary: ", studentID)

studentID[112] = "Stan"

print("Updated Dictionary: ", studentID)

Output

Initial Dictionary:  [111: "Eric", 113: "Butters", 112: "Kyle"]
Updated Dictionary:  [111: "Eric", 113: "Butters", 112: "Stan"]

In the above example, we have created a dictionary named studentID. Initially, the value associated with the key 112 is "Kyle". Now, notice the line,

studentID[112] = "Stan"

Here, we have changed the value associated with the key 112 to "Stan".


Access Elements from Dictionary

In Swift, we can access the keys and values of a dictionary independently.

1. Access Keys Only

 

We use the keys property to access all the keys from the dictionary. For Example,

var cities = ["Nepal":"Kathmandu", "China":"Beijing", "Japan":"Tokyo"]

print("Dictionary: ", cities)

// cities.keys return all keys of cities
var countryName  = Array(cities.keys)

print("Keys: ", countryName)

Output

Dictionary:  ["Nepal": "Kathmandu", "Japan": "Tokyo", "China": "Beijing"]
Keys:  ["Nepal", "Japan", "China"]

2. Access Values Only

Similarly, we use the values property to access all the values from the dictionary. For Example,

var cities = ["Nepal":"Kathmandu", "China":"Beijing", "Japan":"Tokyo"]

print("Dictionary: ", cities)

// cities.values return all values of cities
var countryName  = Array(cities.values)

print("Values: ", countryName)

Output

Dictionary:  ["Nepal": "Kathmandu", "China": "Beijing", "Japan": "Tokyo"]
Values:  ["Kathmandu", "Beijing", "Tokyo"]

Remove an Element from a Dictionary

We use the removeValue() method to remove an element from the dictionary. For example,

var studentID = [111: "Eric", 112: "Kyle", 113: "Butters"]

print("Initial Dictionary: ", studentID)

var removedValue  = studentID.removeValue(forKey: 112)

print("Dictionary After removeValue(): ", studentID)

Output

Initial Dictionary:  [113: "Butters", 111: "Eric", 112: "Kyle"]
Dictionary After removeValue():  [111: "Eric", 113: "Butters"]

Here, we have created a dictionary named studentID. Notice the

var removedValue  = studentID.removeValue(forKey: 112)

The removeValue() method removes the element associated with the key 112.

Note: We can also use removeAll() function to remove all elements of a dictionary.


Other Dictionary Methods

Method Description
sorted() sorts dictionary elements
shuffled() changes the order of dictionary elements
contains() checks if the specified element is present
randomElement() returns a random element from the dictionary
firstIndex() returns the index of the specified element

Iterate Over a Dictionary

We use the for loop to iterate over the elements of a dictionary. For example,

var classification = ["Fruit": "Apple", "Vegetable": "Broccoli", "Beverage": "Milk"]

print("Keys: Values")

for (key,value) in classification {
  print("\(key): \(value)")
}

Output

Keys: Values
Vegetable: Broccoli
Beverage: Milk
Fruit: Apple

Find Number of Dictionary Elements

We can use the count property to find the number of elements present in a dictionary. For example,

var studentID = [111: "Eric", 112: "Kyle", 113: "Butters"]
print(studentID.count)

Output

3

Create an Empty Dictionary

In Swift, we can also create an empty dictionary. For example,

var emptyDictionary =  [Int: String]()
print("Empty Dictionary: ",emptyDictionary)

Output

Empty Dictionary:  [:]

In the above example, we have created an empty dictionary. Notice the expression

[Int: String]()

Here,

  • Int specifies that keys of the dictionary will be of integer type
  • String specifies that values of the dictionary will be of String type.

Note: It is compulsory to specify the data type of dictionary while creating an empty dictionary.

Related Articles