Store and update a Swift Dictionary in NSUserDefaults Xcode

大城市里の小女人 提交于 2020-01-02 08:40:08

问题


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.

dict is my Dictionary variable with Strings as values.

I also have code updating the NSUserDefaults but it appears to be functioning.

Thanks so much in advance!


回答1:


Guess your Xcode's version is below 6.3.

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
    }

}


来源:https://stackoverflow.com/questions/30264345/store-and-update-a-swift-dictionary-in-nsuserdefaults-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!