我正在尝试对结构进行编码
struct Configuration : Encodable, Decodable {
private enum CodingKeys : String, CodingKey {
case title = "title"
case contents = "contents"
}
var title : String?
var contents: [[Int]]?
}
Run Code Online (Sandbox Code Playgroud)
转换成 JSON 以存储在 UserDefaults.standard 的本地键中。我有以下代码:
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
Run Code Online (Sandbox Code Playgroud)
打印返回:
jsonString = Configuration(title: Optional("config"), …Run Code Online (Sandbox Code Playgroud)