Save and retrieve Codable objects to UserDefaults

Swift

Because why not!

Use this extension to save and retrieve Codable objects to and from UserDefaults

swift

public extension UserDefaults { func object<T: Codable>( _ type: T.Type, forKey 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) } }
Usage example:
struct User: Codable { let name: String } let john = User(name: "John") UserDefaults.standard.set(object: john, forKey: "user") let name = UserDefaults.standard.object(User.self, forKey: "user") // john

If you want to take this a bit further, check out UserDefaultsStore, a very light library to store and retrieve -reasonable amount 😅- of Codable objects, in a couple lines of code!