Skip to content

Instantly share code, notes, and snippets.

@ignotusverum
Created May 18, 2020 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ignotusverum/0cb9b57eef021eed3680530df519cedf to your computer and use it in GitHub Desktop.
Save ignotusverum/0cb9b57eef021eed3680530df519cedf to your computer and use it in GitHub Desktop.
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