Swift Dictionaries
Swift dictionaries are used to store unordered collections of data of the same type. Swift dictionaries enforce type checking on their elements, and an error will occur if the types do not match.
Each value (value) in a Swift dictionary is associated with a unique key (key), which acts as an identifier for that value data in the dictionary.
Unlike items in an array, items in a dictionary do not have a specific order. We use dictionaries when we need to access data through an identifier (key). This approach is largely the same as how we use a dictionary in the real world to look up the definition of a word.
There is no type restriction for keys in a Swift dictionary; they can be integers or strings, but they must be unique.
If you create a dictionary and assign it to a variable, the dictionary created is mutable. This means that after the dictionary is created, you can change its items by adding, deleting, or modifying them. If you assign a dictionary to a constant, the dictionary is immutable, and neither its size nor its content can be changed.
* * *
## Creating a Dictionary
We can use the following syntax to create an empty dictionary of a specific type:
var someDict = [KeyType: ValueType]()
The following is a simple syntax for creating an empty dictionary where the key type is Int and the value type is String:
var someDict = [Int: String]()
The following is an example of creating a dictionary:
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
* * *
## Accessing a Dictionary
We can access the elements of a dictionary based on its key index, using the following syntax:
var someVar = someDict
We can learn how to create, initialize, and access a dictionary through the following example:
import Cocoavar someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]var someVar = someDictprint( "Value for key = 1 is \(someVar)" )print( "Value for key = 2 is \(someDict)" )print( "Value for key = 3 is \(someDict)" )
The output of the above program execution is:
Value for key = 1 is Optional("One") Value for key = 2 is Optional("Two") Value for key = 3 is Optional("Three")
* * *
## Modifying a Dictionary
We can use **updateValue(forKey:)** to add or update the content of a dictionary. If the key does not exist, the value is added; if it exists, the value corresponding to the key is updated. The updateValue(_:forKey:) method returns an Optional value. An example is as follows:
import Cocoavar someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]var oldVal = someDict.updateValue("One new value", forKey: 1)var someVar = someDictprint( "Old value for key = 1 is \(oldVal)" )print( "Value for key = 1 is \(someVar)" )print( "Value for key = 2 is \(someDict)" )print( "Value for key = 3 is \(someDict)" )
The output of the above program execution is:
Old value for key = 1 is Optional("One") Value for key = 1 is Optional("One new value") Value for key = 2 is Optional("Two") Value for key = 3 is Optional("Three")
You can also modify the value of a dictionary by specifying a key, as shown below:
import Cocoavar someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]var oldVal = someDict someDict = "One new value"var someVar = someDictprint( "Old value for key = 1 is \(oldVal)" )print( "Value for key = 1 is \(someVar)" )print( "Value for key = 2 is \(someDict)" )print( "Value for key = 3 is \(someDict)" )
The output of the above program execution is:
Old value for key = 1 is Optional("One") Value for key = 1 is Optional("One new value") Value for key = 2 is Optional("Two") Value for key = 3 is Optional("Three")
* * *
## Removing Key-Value Pairs
We can use the **removeValueForKey()** method to remove a key-value pair from a dictionary. If the key exists, this method returns the removed value; if it does not exist, it returns nil. An example is as follows:
import Cocoavar someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]var removedValue = someDict.removeValue(forKey: 2)print( "Value for key = 1 is \(someDict)" )print( "Value for key = 2 is \(someDict)" )print( "Value for key = 3 is \(someDict)" )
The output of the above program execution is:
Value for key = 1 is Optional("One") Value for key = 2 is nil Value for key = 3 is Optional("Three")
You can also remove a key-value pair by setting the value for the specified key to nil. An example is as follows:
import Cocoavar someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"] someDict = nilprint( "Value for key = 1 is \(someDict)" )print( "Value for key = 2 is \(someDict)" )print( "Value for key = 3 is \(someDict)" )
The output of the above program execution is:
Value for key = 1 is Optional("One") Value for key = 2 is nil Value for key = 3 is Optional("Three")
* * *
## Iterating Over a Dictionary
We can use a **for-in** loop to iterate over the key-value pairs in a dictionary. An example is as follows:
import Cocoavar 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 execution is:
Dictionary key 2 - Dictionary value TwoDictionary key 3 - Dictionary value ThreeDictionary key 1 - Dictionary value One
We can also use the enumerate() method to iterate over a dictionary, which returns the dictionary's index and (key, value) pairs. An example is as follows:
import Cocoavar 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 execution 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 a Dictionary to an Array
You can extract the key-value pairs of a dictionary and convert them into independent arrays. An example is as follows:
import Cocoavar someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]let dictKeys = (someDict.keys)let dictValues = (someDict.values)print("Output dictionary keys(key)")for (key) in dictKeys { print("\(key)")}print("Output dictionary values(value)")for (value) in dictValues { print("\(value)")}
The output of the above program execution is:
Output dictionary keys(key)231Output dictionary values(value)TwoThreeOne
* * *
## count Property
We can use the read-only **count** property to calculate how many key-value pairs a dictionary has:
import Cocoavar someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]var someDict2:[Int:String] = [4:"Four", 5:"Five"]print("someDict1 contains \(someDict1.count) key-value pairs")print("someDict2 contains \(someDict2.count) key-value pairs")
The output of the above program execution is:
someDict1 contains 3 key-value pairs someDict2 contains 2 key-value pairs
* * *
## isEmpty Property
We can use the read-only property **isEmpty** to determine whether a dictionary is empty, which returns a Boolean value:
import Cocoavar 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 execution is:
someDict1 = false someDict2 = false someDict3 = true
YouTip