Last active
April 10, 2022 03:22
-
-
Save agrawalsuneet/2546e6c36c01d8ac4808fce3a781e819 to your computer and use it in GitHub Desktop.
Easy way to store codables into UserDefaults
This file contains hidden or 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
//MARK: - UserDefaults + Codable | |
extension UserDefaults { | |
func storeCodable<T: Codable>(_ object: T, key: String) { | |
do { | |
let data = try JSONEncoder().encode(object) | |
UserDefaults.standard.set(data, forKey: key) | |
} catch let error { | |
print("Error encoding: \(error)") | |
} | |
} | |
func retrieveCodable<T: Codable>(for key: String) -> T? { | |
do { | |
guard let data = UserDefaults.standard.data(forKey: key) else { | |
return nil | |
} | |
return try JSONDecoder().decode(T.self, from: data) | |
} catch let error { | |
print("Error decoding: \(error)") | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment