Created
July 13, 2021 12:13
-
-
Save atierian/79a596df2fbc505705e845055b286a41 to your computer and use it in GitHub Desktop.
Codable UserDefaults PropertyWrapper
This file contains hidden or 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
@propertyWrapper | |
struct CodableUserDefault<Value: Codable> { | |
let key: String | |
var wrappedValue: Value? { | |
get { | |
UserDefaults.standard.data(forKey: key).flatMap { | |
try? JSONDecoder().decode(Value.self, from: $0) | |
} | |
} | |
nonmutating set { | |
let data = try? JSONEncoder().encode(newValue) | |
UserDefaults.standard.setValue(data, forKey: key) | |
} | |
} | |
var projectedValue: Self { self } | |
func removeValue() { | |
UserDefaults.standard.removeObject(forKey: key) | |
} | |
} | |
struct Foo: Codable { | |
let bar: Int | |
let baz: Bool | |
let quux: String | |
} | |
// MARK: Usage | |
enum UserDefaultValues { | |
@CodableUserDefault(key: "MyApp.myKey") | |
static var someValue: Foo? | |
} | |
let foo = Foo(bar: 1, baz: true, quux: "hello world") | |
UserDefaultValues.someValue = foo | |
UserDefaultValues.$someValue.removeValue() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment