Skip to content

Instantly share code, notes, and snippets.

@atierian
Created August 28, 2020 01:28
Show Gist options
  • Save atierian/196347d666790c2a425a4c8de243fb27 to your computer and use it in GitHub Desktop.
Save atierian/196347d666790c2a425a4c8de243fb27 to your computer and use it in GitHub Desktop.
Store and retrieve Codable objects in UserDefaults
func object<T: Codable>(_ type: T.Type, with key: String, usingDecoder decoder: JSONDecoder = JSONDecoder()) -> T? {
guard let data = value(forKey: key) as? Data else { return nil }
return try? decoder.decode(type.self, from: data)
}
func set<T: Codable>(object: T, forKey key: String, usingEncoder encoder: JSONEncoder = JSONEncoder()) {
let data = try? encoder.encode(object)
set(data, forKey: key)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment