How to save struct to NSUserDefaults in Swift 2.0

后端 未结 2 1948
一向
一向 2021-01-07 10:35

I have a struct named Jarand I would like to save an array of them to NSUserDefaults. Here is the jar struct code:

struct Jar {

    let name:          


        
2条回答
  •  时光取名叫无心
    2021-01-07 11:29

    For saving to user defaults you have a couple of options: Have the object conform to NSCoding, or implement methods that convert it to/from an NSDictionary, and save that.

    Something like this:

    func dictionaryFromJar() -> NSDictionary
    {
       let dictionary: [AnyObject: AnyObject] = ["name": name, "amount": amount]
       return dictionary
    }
    

    I think the automatic bridging between Swift dictionaries and NSDictionary would work here, but I'm not positive. My swift is getting a little rusty. :(

提交回复
热议问题