Created
December 23, 2021 15:39
-
-
Save sukov/44e67730615c76b1a3cc42a2ab43cd7c to your computer and use it in GitHub Desktop.
Codable additions to 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 { | |
/// Sets the codable value of the specified key. | |
func set<Element: Codable>(_ value: Element, forKey key: String) { | |
let data = try? JSONEncoder().encode(value) | |
UserDefaults.standard.setValue(data, forKey: key) | |
} | |
/// Returns the codable value associated with the specified key. | |
func codable<Element: Codable>(forKey key: String) -> Element? { | |
guard let data = UserDefaults.standard.data(forKey: key) else { return nil } | |
let element = try? JSONDecoder().decode(Element.self, from: data) | |
return element | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment