// Dictionaty<key,Value>
// subscript(key: Key) -> Value?
// key can be Int, Double, String .... any Type: Hashable
// value can be Any (any number, string, struct, enumeration .... class)
var dict: Dictionary<Int,Int> = [1:1]
// key value
dict[10] = 100
dict[1] = 64364
dict[76575] = 1
dict.forEach { (key, value) -> () in
print("storage for key: \(key) has value: \(value)")
/*
storage for key: 76575 has value: 1
storage for key: 1 has value: 64364
storage for key: 10 has value: 100
*/
}
var dict2 = [1:"alfa",2:"beta",3:"game"] // [2: "beta", 3: "game", 1: "alfa"]
dict2.forEach { (key, value) -> () in
print("storage for key: \(key) has value: \(value)")
/*
storage for key: 2 has value: beta
storage for key: 3 has value: game
storage for key: 1 has value: alfa
*/
}
let key = 2
dict2.updateValue("HELLO", forKey: key) // returns string "beta" (old stored value)
print("now the value for key \(key) has value:", dict2[key])
/*
now the value for key 2 has value: Optional("HELLO")
why Optional?
*/
print("the value for key \(-3) has value:", dict2[-3])
/*
the value for key -3 has value: nil
How to remove value?
*/
dict2.removeValueForKey(1) // returns string "alfa" (old value)
dict2[1] // return nil, as expected
您必须将开关的值保存为 Bool 对于键 cellNumber 为 String
var dict: [String:Bool] = [:]
for i in 10...15 {
let j = i % 3
dict.updateValue(j == 0, forKey: "switch\(i)")
}
print(dict)
/*
["switch12": true, "switch13": false, "switch11": false, "switch14": false, "switch10": false, "switch15": true]
*/