title: Swift saving and retrieving custom object from UserDefaults
body: <p>I have this in Playground using Swift 3, Xcode 8.0:</p>
  <pre><code>import Foundation
  class Person: NSObject, NSCoding {
      var name: String
      var age: Int
      init(name: String, age: Int) {
          self.name = name
          self.age = age
      }
      required convenience init(coder aDecoder: NSCoder) {
          let name = aDecoder.decodeObject(forKey: &quot;name&quot;) as! String
          let age = aDecoder.decodeObject(forKey: &quot;age&quot;) as! Int
          self.init(
              name: name,
              age: age
          )
      }
      func encode(with aCoder: NSCoder) {
          aCoder.encode(name, forKey: &quot;name&quot;)
          aCoder.encode(age, forKey: &quot;age&quot;)
      }
  }
  </code></pre>
  <hr />
  <p>create array of Person</p>
  <pre><code>let newPerson = Person(name: &quot;Joe&quot;, age: 10)
  var people = [Person]()
  people.append(newPerson)
  </code></pre>
  <hr />
  <p>encode the array</p>
  <pre><code>let encodedData = NSKeyedArchiver.archivedData(withRootObject: people)
  print(&quot;encodedData: \(encodedData))&quot;)
  </code></pre>
  <hr />
  <p>save to userDefaults</p>
  <pre><code>let userDefaults: UserDefaults = UserDefaults.standard()
  userDefaults.set(encodedData, forKey: &quot;people&quot;)
  userDefaults.synchronize()
  </code></pre>
  <hr />
  <p>check</p>
  <pre><code>print(&quot;saved object: \(userDefaults.object(forKey: &quot;people&quot;))&quot;)
  </code></pre>
  <hr />
  <p>retreive from userDefaults</p>
  <pre><code>if let data = userDefaults.object(forKey: &quot;people&quot;) {
      let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: data as! Data)
      print(&quot;myPeopleList: \(myPeopleList)&quot;)
  }else{
      print(&quot;There is an issue&quot;)
  }
  </code></pre>
  <hr />
  <p>just check the archived data</p>
  <pre><code>if let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: encodedData){
     print(&quot;myPeopleList: \(myPeopleList)&quot;)
  }else{
     print(&quot;There is an issue&quot;)
  }
  </code></pre>
  <p>I'm not able to correctly save the data object to userDefaults, and in addition, the check at the bottom creates the error:</p>
  <blockquote>
  <p>Fatal error: Unexpectedly found nil while unwrapping an Optional value</p>
  </blockquote>
  <p>The &quot;check&quot; line also shows the saved object is nil. Is this an error in my object's NSCoder?</p>