Storing a dictionary in swift in permanent storage

2 Solutions Collect From Internet About “Storing a dictionary in swift in permanent storage”

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)
    }
}

Your code is fine. Your only problem is, that you pass the wrong object to your NSUserDefaults. You should pass the dic instead of array.

So change that:

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

to that:

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