Swift Introduction | Arrays and Dictionaries | Dictionaries
An array stores values in order and retrieves each value with a numeric index. Sometimes it is more convenient to manage values by name instead of by number.
Use a dictionary in such cases. A dictionary manages values with keys. Each value has a key instead of an index number, and you use that key to retrieve or change the value.
Creating a Dictionary
var variable : [Type : Type] = [Type : Type]()
var variable : [Type : Type] = [key1 : value1, key2 : value2, ...]
Accessing Values
variable = dictionary[key]
dictionary[key] = value
Repetition with for-in
for (variable1, variable2) in dictionary {
... repeated processing ...
}
Specify two data types inside square brackets: the types of the keys and values. For example, to store Int values with String keys, write [String : Int]. Assign [String : Int]() to a variable to create an empty dictionary.
Unlike an array, a dictionary does not require a predefined number of storage locations. When you store a value with a key, that key is added to the dictionary. If the same key already exists, its value is updated.
The for-in syntax differs slightly from its use with arrays. After for, provide a tuple such as (variable1, variable2). The dictionary’s key and value are assigned to the respective variables.
The following example demonstrates this behavior.
let data:[String:Int] = ["Korean":98,"Mathematics":76,"English":54]
var total = 0
for (key, val) in data {
total += val
println("add \(key)")
}
println("Total: \(total)")
This example stores scores for three subjects in a dictionary, retrieves the elements, and calculates their total. Each retrieved key is printed as add 〇〇, followed by the final total.