简体   繁体   中英

How to store and retrieve Dictionary value types in Swift

I was having trouble storing a Dictionary in the NSUserDefaults, and then I had trouble retrieving the values. After a failed search on the web, I finally figured it out and so I hope this helps you with this same issue.

Define your variables for NSUserDefaults, Dictionary and key:

let defaults = NSUserDefaults.standardUserDefaults()
var myDictionary = Dictionary<String, Int>()
let myKey = "Key"

How to save your dictionary:

defaults.setObject(myDictionary, forKey: myKey)

How to retrieve your dictionary:

myDictionary = defaults.dictionaryForKey(myKey) as! Dictionary<String, Int>

NOTE: make sure that your data types are the same as the way you set them up.

*** FYI, this is using Xcode 6.3.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM