What are dictionaries in Swift?
A dictionary is a data container that holds key-value pairs in an unordered manner. These keys, and their corresponding values, can all only be of one type. Each value has to be associated with a
Declaring a dictionary
While declaring a dictionary, it is optional to give data types for the key value pairs as Swift can infer these data types if we do not supply them during the declaration. An empty dictionary is declared by specifying the key (value data type inside square brackets []).
import Swift// initializing an empty dictionarylet firstDict:[Int:String] = [:]print(firstDict)// initializing a dictionary and letting swift infer data typelet secondDict = ["a":1, "b":2, "c":3, ]print(secondDict)// initializing a dictionary and giving the data types for the key-value pairsvar thirdDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]print(thirdDict)
Accessing and modifying data in a dictionary
The easiest and most common way to access an element in a dictionary is to use the key as a subscript. Swift also:
- allows us to print our own message if a key is not present in the dictionary.
- modify a value stored against a key using the
updateValuefunction or equating a new value to the subscript.
The code used to do this is shown below:
import Swift// accessing the valuesvar myDict:[String:Int] = ["a":1, "b":2, "c":3, "d":4, ]print(myDict["a"]!)print(myDict["c"]!)// accessing keys not available in the dictionaryif let myVal = myDict["h"] {print("The value is \(myVal).")} else {print("The value is not present against the key")}// modifying the valuesvar o = myDict.updateValue(24, forKey: "c")print("Modified value for the key 'c'")print(myDict["c"]!)print("Modified value for the key 'c'")myDict["c"] = 56print(myDict["c"]!)
Iterating over keys and values in a dictionary
The code below shows how to iterate over key-value pairs in Swift:
import Swift// accessing the valuesvar myDict = ["a":1, "b":2, "c":3, "d":4, ]for (k, v) in myDict {print("The key '\(k)' holds the value '\(v)'.")}