Swift Dictionary
Swift dictionaries are used to store collections of data that are unordered and of the same type. Swift dictionaries enforce type checking, and if the types do not match, an error will be thrown.
Each value in a Swift dictionary is associated with a unique key, which serves as the identifier for that value in the dictionary.
Unlike array items, dictionary items do not have a specific order. We use dictionaries when we need to access data by an identifier (key), which is similar to how we look up meanings in a real-world dictionary.
The keys in a Swift dictionary can be of any type, such as integers or strings, but they must be unique.
If a dictionary is created and assigned to a variable, it can be modified. This means that after the dictionary is created, items can be added, removed, or changed. If a dictionary is assigned to a constant, it cannot be modified, and both its size and content are immutable.
Creating a Dictionary
We can create an empty dictionary of a specific type using the following syntax:
var someDict = [KeyType: ValueType]()
Here is a simple syntax for creating an empty dictionary with keys of type Int and values of type String:
var someDict = [Int: String]()
Below is an example of creating a dictionary instance:
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
Accessing a Dictionary
We can access elements of a dictionary by their index, using the following syntax:
var someVar = someDict[key]
We can learn how to create, initialize, and access a dictionary through the following example:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someVar = someDict[1]
print("The value for key = 1 is \(someVar)")
print("The value for key = 2 is \(someDict[2])")
print("The value for key = 3 is \(someDict[3])")
The output of the above program is:
The value for key = 1 is Optional("One")
The value for key = 2 is Optional("Two")
The value for key = 3 is Optional("Three")
Modifying a Dictionary
We can use the updateValue(forKey:) method to add or update dictionary content. If the key does not exist, it adds the value; if it does, it updates the value associated with the key. The updateValue(_:forKey:) method returns an Optional value. Here is an example:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict.updateValue("New value for One", forKey: 1)
var someVar = someDict[1]
print("The old value for key = 1 is \(oldVal)")
print("The value for key = 1 is \(someVar)")
print("The value for key = 2 is \(someDict[2])")
print("The value for key = 3 is \(someDict[3])")
The output of the above program is:
The old value for key = 1 is Optional("One")
The value for key = 1 is Optional("New value for One")
The value for key = 2 is Optional("Two")
The value for key = 3 is Optional("Three")
You can also modify the value of a dictionary by specifying the key, as shown below:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict[1]
someDict[1] = "New value for One"
var someVar = someDict[1]
print("The old value for key = 1 is \(oldVal)")
print("The value for key = 1 is \(someVar)")
print("The value for key = 2 is \(someDict[2])")
print("The value for key = 3 is \(someDict[3])")
The output of the above program is:
The old value for key = 1 is Optional("One")
The value for key = 1 is Optional("New value for One")
The value for key = 2 is Optional("Two")
The value for key = 3 is Optional("Three")
Removing a Key-Value Pair
To remove a key-value pair from a dictionary, you can use the removeValue(forKey:) method or set the value to nil. Here is an example:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var removedValue = someDict.removeValue(forKey: 2)
print("The removed value is \(removedValue)")
print("The dictionary is now \(someDict)")
The output of the above program is:
The removed value is Optional("Two")
The dictionary is now [1: "One", 3: "Three"]
We can use the removeValueForKey() method to remove a dictionary key-value pair. If the key exists, this method returns the removed value; if it does not exist, it returns nil. Here is an example:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var removedValue = someDict.removeValue(forKey: 2)
print( "The value for key = 1 is \(someDict[1])" )
print( "The value for key = 2 is \(someDict[2])" )
print( "The value for key = 3 is \(someDict[3])" )
The output of the above program is:
The value for key = 1 is Optional("One")
The value for key = 2 is nil
The value for key = 3 is Optional("Three")
You can also remove a key-value pair by setting the key's value to nil. Here is an example:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
someDict[2] = nil
print( "The value for key = 1 is \(someDict[1])" )
print( "The value for key = 2 is \(someDict[2])" )
print( "The value for key = 3 is \(someDict[3])" )
The output of the above program is:
The value for key = 1 is Optional("One")
The value for key = 2 is nil
The value for key = 3 is Optional("Three")
Traversing a Dictionary
We can use the for-in loop to traverse through the key-value pairs in a dictionary. Here is an example:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict {
print("Dictionary key \(key) - Dictionary value \(value)")
}
The output of the above program is:
Dictionary key 2 - Dictionary value Two
Dictionary key 3 - Dictionary value Three
Dictionary key 1 - Dictionary value One
We can also use the enumerate() method to traverse a dictionary, which returns the index and (key, value) pair. Here is an example:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict.enumerated() {
print("Dictionary key \(key) - Dictionary (key, value) pair \(value)")
}
The output of the above program is:
Dictionary key 0 - Dictionary (key, value) pair (2, "Two")
Dictionary key 1 - Dictionary (key, value) pair (3, "Three")
Dictionary key 2 - Dictionary (key, value) pair (1, "One")
Converting Dictionary to Arrays
You can extract the key-value pairs of a dictionary and convert them into separate arrays. Here is an example:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
let dictKeys = [Int](someDict.keys)
let dictValues = [String](someDict.values)
print("Output the keys of the dictionary")
for (key) in dictKeys {
print("\(key)")
}
print("Output the values of the dictionary")
for (value) in dictValues {
print("\(value)")
}
The output of the above program is:
Output the keys of the dictionary
2
3
1
Output the values of the dictionary
Two
Three
One
count Property
We can use the read-only count property to determine the number of key-value pairs in a dictionary:
import Cocoa
var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]
print("Total items in someDict1 = \(someDict1.count)")
print("Total items in someDict2 = \(someDict2.count)")
The output of the above program is:
Total items in someDict1 = 3
Total items in someDict2 = 2
print("someDict1 contains \(someDict1.count) key-value pairs")
print("someDict2 contains \(someDict2.count) key-value pairs")
The output of the above program is:
someDict1 contains 3 key-value pairs
someDict2 contains 2 key-value pairs
isEmpty Property
We can determine if a dictionary is empty by using the read-only property isEmpty, which returns a Boolean value:
import Cocoa
var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]
var someDict3:[Int:String] = [Int:String]()
print("someDict1 = \(someDict1.isEmpty)")
print("someDict2 = \(someDict2.isEmpty)")
print("someDict3 = \(someDict3.isEmpty)")
The output of the above program is:
someDict1 = false
someDict2 = false
someDict3 = true