Swift Introduction | Arrays and Dictionaries | Working with Dictionaries
Like arrays, dictionaries are objects with properties and methods. Call these methods to manipulate dictionary contents. Unlike arrays, dictionaries do not need an insertion method because you can add a new value simply by specifying a key.
Removing the Value for a Specified Key
dictionary.removeValueForKey(key)
Removing All Values
dictionary.removeAll()
Retrieving All Keys
variable = dictionary.keys
Retrieving All Stored Values
variable = dictionary.values
Retrieving the Number of Elements
variable : Int = dictionary.count
Pay particular attention to keys and values. These properties store the keys and values respectively. Their return values are instances of an unfamiliar collection class called LazyBidirectionalCollection, but you can retrieve their values sequentially with for-in.
The following example works with a dictionary.
var data:[String:Int] = ["Korean":98,"Mathematics":76,"English":54]
let keys = data.keys
let vals = data.values
for key in keys {
println(key)
}
for val in vals {
println(val)
}
This code retrieves the dictionary’s keys and values, then prints them with for-in. The stored keys and values are displayed.