Skip to content

Instantly share code, notes, and snippets.

@Jegge
Created January 30, 2022 15:37
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 Jegge/dc6713e1fdf53ccddf002fced973f7c4 to your computer and use it in GitHub Desktop.
Save Jegge/dc6713e1fdf53ccddf002fced973f7c4 to your computer and use it in GitHub Desktop.
Allows to store / retrieve arbitrary Codable objects to / from UserDefaults.
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