swiftstoragepermanent

Storing a dictionary in swift in permanent storage


this code here throws an error when I run the app

var dic :[NSObject: AnyObject] = ["name":"steph" , "status": "unemployed"]

NSUserDefaults.standardUserDefaults().setObject(array, forKey: "diction")

var retrievedDict = NSUserDefaults.standardUserDefaults().objectForKey("diction")! as NSDictionary

let g = dic["name"]

println(g)

what's wrong with this?


Solution

  • The problem is that the Dictionary key has to be a String. So instead of declaring it [NSObject: AnyObject] you have to declare it as [String: AnyObject]. Also you are trying to load it from dic but you have to load it from retrievedDict.

    update: Xcode 7.2 • Swift 2.1.1

    let dic:[String: AnyObject] = ["name":"steph" , "status": "unemployed"]
    
    NSUserDefaults().setObject(dic, forKey: "diction")
    
    if let retrievedDict = NSUserDefaults().dictionaryForKey("diction") {
        if let g = retrievedDict["name"] as? String {
            print(g)
        }
    }