title: Saving a Codable Struct to UserDefaults with Swift
body: <p>I am trying to encode a struct</p>
  
  <pre><code>struct Configuration : Encodable, Decodable {
      private enum CodingKeys : String, CodingKey {
          case title = "title"
          case contents = "contents"
      }
      var title : String?
      var contents: [[Int]]?
  }
  </code></pre>
  
  <p>into JSON to store in a local key of UserDefaults.standard. I have the following code:</p>
  
  <pre><code>let jsonString = Configuration(title: nameField.text, contents: newContents)
  let info = ["row" as String: jsonString as Configuration]
  print("jsonString = \(jsonString)")
  //trying to save object
  let defaults = UserDefaults.standard
  let recode = try! JSONEncoder().encode(jsonString)
  defaults.set(recode, forKey: "simulationConfiguration")
  //end of saving local
  </code></pre>
  
  <p>The print returns:</p>
  
  <pre><code>jsonString = Configuration(title: Optional("config"), contents: Optional([[4, 5], [5, 5], [6, 5]]))
  </code></pre>
  
  <p>so I believe I am creating the object correctly. However, when I try and retrieve the key the next time I run the simulator I get nothing.
  I put the following in AppDelegate and it always returns No Config.</p>
  
  <pre><code>let defaults = UserDefaults.standard
          let config = defaults.string(forKey: "simulationConfiguration") ?? "No Config"
          print("from app delegate = \(config.description)")
  </code></pre>
  
  <p>Any ideas? Thanks</p>