解释工作不正常
问题描述:
我一直使用的字典在我的代码,他们都工作,我想希望本字典的方式:解释工作不正常
switchState["index"+("\(cellNumber)")] = cellNumber
这里面有个for in
是cellNumber
是变量之一。该cellNumber
代表UISwitch
用户开启。
这本词典继续改写自己,我想不通为什么。该"index"+("\(cellNumber)")
应该给字典一个新的密钥存储cellNumber
是否正确?
我试图将此存储到NSUserDefaults
作为NSDictionary
和swift使我有一个String
的密钥或它不会存储它。所以当我存储Dictionary时只存在一个值。你能看到上述Code
有问题,或者有另一种方法来做到这一点。
感谢您的帮助。
答
// 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