Skip to content

Instantly share code, notes, and snippets.

@jayesh15111988
Last active May 6, 2022 08:33
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 jayesh15111988/c235d9833ad28a405f8ffe31a61fd337 to your computer and use it in GitHub Desktop.
Save jayesh15111988/c235d9833ad28a405f8ffe31a61fd337 to your computer and use it in GitHub Desktop.
Storing custom objects into UserDefaults persistent storage
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)
}
}
}
@jayesh15111988
Copy link
Author

jayesh15111988 commented Jan 27, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment