Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save atierian/79a596df2fbc505705e845055b286a41 to your computer and use it in GitHub Desktop.
Save atierian/79a596df2fbc505705e845055b286a41 to your computer and use it in GitHub Desktop.
Codable UserDefaults PropertyWrapper
@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