How to save struct to NSUserDefaults in Swift 2.0

后端 未结 2 1958
一向
一向 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

    This solution is inspired by @Duncan C. I wrote it more familiar way as we do in case Custom Class encoding and decoding.

    public struct IRDriver {
    
      public var name: String?
      public var amount: Int?
    
      public init() {
    
      }
    
      // Decode
      public init(dictionary: Dictionary){
        name = dictionary["name"] as? String
        amount = dictionary["amount"] as? Int
      }
    
      // Encode
      public func encode() -> Dictionary {
    
        var dictionary : Dictionary = Dictionary()
        dictionary["name"] = name
        dictionary["amount"] = amount
        return dictionary
      }
    
    }
    

提交回复
热议问题