Created
May 18, 2020 03:05
-
-
Save ignotusverum/0cb9b57eef021eed3680530df519cedf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
struct Test1: Codable { | |
var testDate: Date? = nil | |
let name: String | |
let age: Int | |
enum CodingKeys: String, CodingKey { | |
case name | |
case age | |
} | |
} | |
let json = """ | |
{ | |
"name": "test", | |
"age": 30, | |
} | |
""" | |
let jsonData = Data(json.utf8) | |
var test1 = try? JSONDecoder().decode(Test1.self, from: jsonData) | |
test1?.testDate = Date() | |
var currentTest: Test1? { | |
get { | |
let defaults = UserDefaults.standard | |
guard let testData = defaults.object(forKey: "test1") as? Data, | |
let test = try? PropertyListDecoder().decode(Test1.self, | |
from: testData) else { | |
return nil | |
} | |
return test | |
} | |
set { | |
let defaults = UserDefaults.standard | |
defaults.set(try? PropertyListEncoder().encode(newValue), forKey: "test1") | |
} | |
} | |
currentTest = test1 | |
print(test1) | |
print(currentTest) | |
print(currentTest?.testDate) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment