Swift - Dictionaries



Dictionaries are used to store unordered lists of values of the same type. Swift puts strict checking which does not allow you to enter a wrong type in a dictionary even by mistake.

Dictionaries use a unique identifier known as a key to store a value which later can be referenced and looked up through the same key. Unlike arrays, items in a dictionary do not have a specified order. You can use a dictionary when you need to look up values based on their identifiers. In a dictionary, a key can be either an integer or a string without restriction, but it should be unique within a dictionary. Whereas values can be duplicated.

If you assign a created dictionary to a variable, then it is always mutable which means you can change it by adding, removing, or changing its items. But if you assign a dictionary to a constant, then that dictionary is immutable, and its size and contents cannot be changed.

Creating Dictionary in Swift

A dictionary contains a key-value pair. The type of key-value pair can be the same or different means it is not necessary that the type of the key and value should be the same. So we can create a dictionary of a certain type using the following syntax.

Syntax

Following is the syntax for creating a dictionary −

var someDict =  [KeyType: ValueType](key:value)

We can also create a dictionary without specifying its type. In this case, the compiler will automatically get the type of the dictionary based on the assigned value. Following is the syntax for creating a dictionary −

var someArray = [key1: value, key2: value, key3: value3]

Filtering Elements of the Dictionary in Swift

To filter the elements of the dictionary swift provides a pre-defined function named filter(). The filter() function takes a closure as a parameter and returns a new dictionary that contains only those key-value pairs that match the given condition in the closure.

Syntax

Following is the syntax of the filter() function −

func filter(closure)

Example

import Foundation

// Defining and initializing a dictionary
var myDict = [3: "Blue", 4: "Pink", 5:"Green", 7:"Pink"]

// Filtering out only pink color using filter() function
let color = myDict.filter { $0.value == "Pink" }

print(color)

Output

It will produce the following output −

[4: "Pink", 7: "Pink"]

Accessing Dictionaries in Swift

To access the key-value pairs of the given dictionary we can use any of the following methods −

Using Subscript Syntax

We can retrieve a value from a dictionary by using subscript syntax, passing the key of the value we want to retrieve within square brackets immediately after the name of the dictionary.

Syntax

Following is the syntax for accessing dictionaries −

var someVar = someDict[key]

Example

import Foundation

// Defining a dictionary
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

// Accessing the value of key = 1 using subscript syntax
var someVar = someDict[1]

// Checking if the value is not nil before using it
if let result = someVar  {
   print("Value of key = 1 is \(result)")
} else {
   print("Value not found")
}

Output

It will produce the following output −

Value of key = 1 is One

Using keys Property

We can access the key separately using the keys property. This property will return all the keys present in the dictionary.

Syntax

Following is the syntax for the keys property −

dictionary.keys

Example

import Foundation

// Defining a dictionary
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

// Accessing the keys
var output = someDict.keys

print(output)
Output

It will produce the following output −

[1, 2, 3]

Using values Property

We can access the value separately using the values property. This property will return all the values present in the dictionary.

Syntax

Following is the syntax for values property −

dictionary.values

Example

import Foundation

// Defining a dictionary
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

// Accessing the values
var output = someDict.values

print(output)
Output

It will produce the following output −

["Two", "One", "Three"]

Modifying Dictionaries in Swift

To modify the existing value of the associated key Swift provides a predefined method named updateValue(forKey:). If the given key-value pair is not present in the given dictionary, then this method adds that pair to the dictionary. This method returns a replaced value or nil if it adds a new key-value pair.

Syntax

Following is the syntax for the updateValue() function −

func updateValue(value, forKey: key) 

Example

import Foundation

// Declaring dictionary
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

print("Original Dictionary:", someDict)

// Updating the value of key = 2 with new value
// Using updateValue() function
someDict.updateValue("Four", forKey: 2)

// Displaying output
print("Updated Dictionary:", someDict)

Output

It will produce the following output −

Original Dictionary: [1: "One", 2: "Two", 3: "Three"]
Updated Dictionary: [1: "One", 2: "Four", 3: "Three"]

Modifying elements in a Dictionary

We can modify an existing element of a dictionary by assigning a new value at a given key using []. The bracket[] changes the value of the specified key in the given dictionary.

Syntax

Following is the syntax for updating the value −

Dictionary[key] = value

Example

import Foundation

// Declaring dictionary
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

// Updating the value of key = 1 with new value
someDict[1] = "New value of one"

// Displaying the updated value
print("Updated Dictionary:", someDict)
Output

It will produce the following output −

Updated Dictionary: [1: "New value of one", 3: "Three", 2: "Two"]

Remove Key-Value Pairs from a dictionary

To remove key-value pair from a dictionary Swift provides a pre-define function named removeValue(forKey:) method. This method removes the specified key and its related value if it exists and returns the removed value, or returns nil if no value exists.

Syntax

Following is the syntax of the removeValue() property −

Dictionary.removeValue(forKey: Key)

Example

import Foundation

// Declaring dictionary
var dict = [101: "Blue", 102: "Pink", 103: "Black", 104: "Brown"]

print("Original Dictionary:", dict)

// Removing a key-Value pair
// Using removeValue() method
dict.removeValue(forKey: 102)

// Displaying output
print("Updated Dictionary:", dict)

Output

It will produce the following output −

Original Dictionary: [102: "Pink", 103: "Black", 104: "Brown", 101: "Blue"]
Updated Dictionary: [103: "Black", 104: "Brown", 101: "Blue"]

Removing all the elements at once

Swift provides one more pre-defined method named removeAll(). This method removes all the keys and their associated values from the given dictionary.

Example

import Foundation

// Declaring dictionary
var dict = [101: "Blue", 102: "Pink", 103: "Black", 104: "Brown"]

print("Original Dictionary:", dict)

// Removing all the key-Value pairs
// Using removeAll() method
dict.removeAll()

// Displaying output
print("Updated Dictionary:", dict)
Output

It will produce the following output −

Original Dictionary: [101: "Blue", 103: "Black", 104: "Brown", 102: "Pink"]
Updated Dictionary: [:]

Iterating Over a Dictionary in Swift

To iterate over a dictionary Swift provides a for-in loop. The for-in loop iterates over the entire set of key-value pairs in a dictionary.

Example

import Foundation

// Declaring dictionary
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

// Iterating over the dictionary
// Using for-in loop
for (key, value) in someDict {
   print("Dictionary key \(key) -  Dictionary value \(value)")
}

Output

It will produce the following output −

Dictionary key 3 -  Dictionary value Three
Dictionary key 1 -  Dictionary value One
Dictionary key 2 -  Dictionary value Two

Using the Enumerated() Function

We can also use the enumerated() function along with the for-in loop, it returns the index of the item along with its (key, value) pair.

Example

import Foundation

// Declaring dictionary
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

// Getting the index of the key-value pairs
// Using enumerated() function
for (key, value) in someDict.enumerated() {
   print("Dictionary key \(key) -  Dictionary value \(value)")
}
Output

It will produce the following output −

Dictionary key 0 -  Dictionary value (key: 1, value: "One")
Dictionary key 1 -  Dictionary value (key: 2, value: "Two")
Dictionary key 2 -  Dictionary value (key: 3, value: "Three")

Converting Dictionary to Array in Swift

To convert a dictionary into an array, extract a list of key-value pairs from a given dictionary to build separate arrays for both keys and values.

Example

import Foundation

// Declaring dictionary
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

// Declaring two arrays and storing keys and values separately
let dictKeys = [Int](someDict.keys)
let dictValues = [String](someDict.values)

// Displaying the arrays
print("Print Dictionary Keys")
for (key) in dictKeys {
   print("\(key)")
}

print("Print Dictionary Values")
for (value) in dictValues {
   print("\(value)")
}

Output

It will produce the following output −

Print Dictionary Keys
1
3
2
Print Dictionary Values
One
Three
Two

The "count" Property of Dictionary

The count property is used to count the total number of elements present in the dictionary.

Syntax

Following is the syntax of the count property −

Dictionary.count

Example

import Foundation
// Declaring dictionaries
var someDict1 : [Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2 : [Int:String] = [4:"Four", 5:"Five"]

// Counting the elements of dictionaries
// Using count property
var size1 = someDict1.count
var size2 = someDict2.count

print("Total items in someDict1 = \(size1)")
print("Total items in someDict2 = \(size2)")

Output

It will produce the following output −

Total items in someDict1 = 3
Total items in someDict2 = 2

The "empty" Property of Dictionary

The empty property is used to check whether the given dictionary is empty or not. This property will return true if the given dictionary is empty. If the given dictionary contains some element, then this property will return false.

Syntax

Following is the syntax of the empty property −

Dictionary.isEmpty 

Example

import Foundation

// Declaring dictionaries
var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]
var someDict3:[Int:String] = [Int:String]()

// Checking if the dictionary is empty or not
// Using isEmpty property
print("someDict1 = \(someDict1.isEmpty)")
print("someDict2 = \(someDict2.isEmpty)")
print("someDict3 = \(someDict3.isEmpty)")

Output

It will produce the following output −

someDict1 = false
someDict2 = false
someDict3 = true
Advertisements