Store and update a Swift Dictionary in NSUserDefau

2019-05-10 11:02发布

问题:

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
    }

}