存储并更新NSUserDefaults Xcode中的Swift Dictionary [英] Store and update a Swift Dictionary in NSUserDefaults Xcode
问题描述
当用户输入值时,我想存储和更新字典。一切似乎都运行到这段代码,应用程序崩溃:
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]
}
}
错误消息说anyObject不能转换为[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.
dict是我的Dictionary变量,使用Strings作为值。
dict is my Dictionary variable with Strings as values.
我也有更新NSUserDefaults的代码,但似乎正常运行。
I also have code updating the NSUserDefaults but it appears to be functioning.
非常感谢!
推荐答案
猜测Xcode的版本低于6.3。
Guess your Xcode's version is below 6.3.
使用 dictionaryForKey:
而不是 objectForKey:
。字典
不是Swift中的类类型是一个值类型。
Using dictionaryForKey:
instead of objectForKey:
.Dictionary
is not a class type in Swift,it is a value type.
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
}
}
这篇关于存储并更新NSUserDefaults Xcode中的Swift Dictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!