Store and update Swift dictionary in NSUserDefaults Xcode

I would like to save and update the dictionary when the user enters a value. Everything seems to work up to 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 does not convert to [String: String]. It suggests adding! After, but then the application crashes."

dict is my Dictionary variable with strings as values.

I also have code updating NSUserDefaults, but it works.

Thank you very much in advance!

+3


source to share


1 answer


Let's assume your Xcode 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
    }

}

      

+2


source







All Articles