How to save struct to NSUserDefaults in Swift 2.0

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: String
    let amount: Int

    init(name: String, amount: Int){ = name
        self.amount = amount

I belive that I will need to convert this to an NSObject to be able to save it. (Because you can’t save a struct directly to NSUserDefaults). My questions are:
How do I convert an array of structs to an NSObject? and How to convert an NSObject back at an array of structs.

  • How to show tableview when user taps searchbar swift
  • Swift 2.2 How to change background color of tab bar controller
  • Detecting available API iOS vs. watchOS in Swift
  • Swift 2 :IBOutlet Collection ! leaks memory
  • Not able to pass self (which implements a protocol) to init method of a class instantiation.(Swift)
  • Distorted sound when changing AVAudioPlayer's rate var in Swift 2.0
  • 2 Solutions Collect From Internet About “How to save struct to NSUserDefaults in Swift 2.0”

    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<String, AnyObject>){
        name = dictionary["name"] as? String
        amount = dictionary["amount"] as? Int
      // Encode
      public func encode() -> Dictionary<String, AnyObject> {
        var dictionary : Dictionary = Dictionary<String, AnyObject>()
        dictionary["name"] = name
        dictionary["amount"] = amount
        return dictionary

    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. 🙁