在 NSUserDefaults Xcode 中存储和更新 Swift 字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30264345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store and update a Swift Dictionary in NSUserDefaults Xcode
提问by GJZ
I would like to store and update a Dictionary when a user enters a value. Everything seems to function until this code, and the application crashes:
我想在用户输入值时存储和更新字典。在这段代码之前,一切似乎都在运行,并且应用程序崩溃了:
override func viewDidLoad() {
super.viewDidLoad()
if NSUserDefaults.standardUserDefaults().objectForKey("dict") != nil {
answersSaved = NSUserDefaults.standardUserDefaults().objectForKey("dict") as [String:String]
}
}
The error message says "anyObject is not convertible to [String:String]. It offers to add ! after the as but then the app crashes.
错误消息说“anyObject 不能转换为 [String:String]。它提供在 as 之后添加 ! 但随后应用程序崩溃。
dict is my Dictionary variable with Strings as values.
dict 是我的字典变量,字符串作为值。
I also have code updating the NSUserDefaults but it appears to be functioning.
我也有更新 NSUserDefaults 的代码,但它似乎正在运行。
Thanks so much in advance!
非常感谢!
回答by tounaobun
Guess your Xcode's version is below 6.3.
猜猜你的 Xcode 版本低于 6.3。
Using dictionaryForKey:
instead of objectForKey:
.Dictionary
is not a class type in Swift,it is a value type.
使用dictionaryForKey:
代替objectForKey:
. Dictionary
不是 Swift 中的类类型,它是一种值类型。
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setValue(["key":"value"], forKey: "answersSaved") // fill data
if let answersSaved = userDefaults.dictionaryForKey("answersSaved") as? [String : String] {
// [NSObject : AnyObject] can be converted to [String : String]
if let value = answersSaved["key"] {
println(value) // value
}
}