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
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 dictionary let firstDict:[Int:String] = [:] print(firstDict) // initializing a dictionary and letting swift infer data type let secondDict = ["a":1, "b":2, "c":3, ] print(secondDict) // initializing a dictionary and giving the data types for the key-value pairs var thirdDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"] print(thirdDict)
The easiest and most common way to access an element in a dictionary is to use the key as a subscript. Swift also:
updateValue
function or equating a new value to the subscript.The code used to do this is shown below:
import Swift // accessing the values var myDict:[String:Int] = ["a":1, "b":2, "c":3, "d":4, ] print(myDict["a"]!) print(myDict["c"]!) // accessing keys not available in the dictionary if let myVal = myDict["h"] { print("The value is \(myVal).") } else { print("The value is not present against the key") } // modifying the values var 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"] = 56 print(myDict["c"]!)
The code below shows how to iterate over key-value pairs in Swift:
import Swift // accessing the values var myDict = ["a":1, "b":2, "c":3, "d":4, ] for (k, v) in myDict { print("The key '\(k)' holds the value '\(v)'.") }
RELATED TAGS
CONTRIBUTOR
View all Courses