Ulrik. S Ulrik. S - 1 year ago 55
Swift Question

How to save / retrieve nested dictionary in NSUserDefault swift?

I'm building an app, in which the user is able to create UITableviewcell that will lead to a different UIViewController editable by the user. I save the user information as such:

level1Dictionary = [String : [String : String]]()

If the user names a UITableViewCell Dog they segue to the viewController and i set
level1Dictionary[dog] = [String : String]()
I now save the dictionary in NSUserdefaults as such
NSUserDefaults.StandardUserDefaults()setObject(level1Dictionary, forKey: "level1Dictionary")
All works fine.

When i restart the app and press my customCreate UITAbleViewCell named dog i want to retrieve what ever information the user stored in
level1Dictionary = [Dog : [String : String]]
I retrieve the information as such within viewdidload:
level1Dictionary = NSUserDefault.standardUserDefaults().objectForKey("level1Dictionary") as? [String : String] ?? [String : String]()
but this returns error: Cannot Convert value of type [String : String]? to expected argument type [String : [String : String]]?

Answer Source

Try this:

NSUserDefault.standardUserDefaults().objectForKey("level1Dictionary") as? [String : [String : String]]?? [String : [String : String]]()