How to make UserDefaults property wrapper

Issue #726

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@propertyWrapper
struct UserDefault<Value> {
let key: String
let defaultValue: Value
let container: UserDefaults = .standard

var wrappedValue: Value {
get {
return container.object(forKey: key) as? Value ?? defaultValue
}
set {
container.set(newValue, forKey: key)
}
}
}

Then we can use it as property and provide default value

1
2
3
final class KeepHistoryService {
@UserDefault(key: "keepHistoryCheckDate", defaultValue: nil)
var checkDate: Date?

Comments