Skip to content

Instantly share code, notes, and snippets.

@sukov
Created December 23, 2021 15:39
Show Gist options
  • Save sukov/44e67730615c76b1a3cc42a2ab43cd7c to your computer and use it in GitHub Desktop.
Save sukov/44e67730615c76b1a3cc42a2ab43cd7c to your computer and use it in GitHub Desktop.
Codable additions to UserDefaults
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