Last active
May 6, 2022 08:33
-
-
Save jayesh15111988/c235d9833ad28a405f8ffe31a61fd337 to your computer and use it in GitHub Desktop.
Storing custom objects into UserDefaults persistent storage
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
struct Employee: Codable { | |
let name: String | |
let ssn: String | |
} | |
private let employeeDataKey = "employee" | |
func encodeObject() { | |
do { | |
let employeeData = try JSONEncoder().encode(Employee(name: "abc def", ssn: "123456789")) | |
UserDefaults.standard.set(employeeData, forKey: employeeDataKey) | |
} catch { | |
print(error.localizedDescription) | |
} | |
} | |
func decodeObject() { | |
if let employeeData = UserDefaults.standard.data(forKey: employeeDataKey) { | |
do { | |
let employeeObject = try JSONDecoder().decode(Employee.self, from: employeeData) | |
print(employeeObject.name) | |
print(employeeObject.ssn) | |
} catch { | |
print(error.localizedDescription) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Accompanying blog post - https://jayeshkawli.ghost.io/ios-swift-storing-custom-objects-into-data-or-userdefaults/