// 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
必須爲關鍵cellNumber保存開關爲布爾值的字符串
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]
*/
感謝您的解釋,我知道一個dicitionary可以是任何東西。但我正在專門討論保存到'NSUserDefaults'。在Swift中,當你想將'NSDictionary'保存爲'NSUserDefaults'時,它只能處理'[String:AnyObject?]'。此外,我在表格中有多個開關,它們的索引都不同。所以如果我可以存儲'索引即。 cellNumber'和字典中'switch'的狀態,然後將它存儲到'NSUserDefaults'中,這將解決我的問題。我會嘗試你最後的建議並讓你知道。謝謝。 – Rico
你麻煩的是,保存(鍵,值)(密鑰,密鑰)字典[「\(密鑰)」] =鍵。但你需要將其保存像字典[「\(鑰匙」] =值WhatEverYouNeed爲有效NSUserDefaults的對。 – user3441734
所以我保存它像這樣'switchState [(「\(cellNumber)」)] = TRUE;但它仍然覆蓋本身我每次調用'.count'詞典中,以確保其正常複製,但每次都只是大小1有什麼想法 – Rico