Created
January 30, 2022 15:37
-
-
Save Jegge/dc6713e1fdf53ccddf002fced973f7c4 to your computer and use it in GitHub Desktop.
Allows to store / retrieve arbitrary Codable objects to / from UserDefaults.
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
extension UserDefaults { | |
func set<T>(encodable object: T, forKey key: String) where T: Encodable { | |
if let data = try? JSONEncoder().encode(object) { | |
set(data, forKey: key) | |
} | |
} | |
func decodable<T>(forKey key: String) -> T? where T: Decodable { | |
if let data = data(forKey: key) { | |
return try? JSONDecoder().decode(T.self, from: data) | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment