0%

UserDefaultsWrapper

又水一篇...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import HandyJSON

extension Bool: HandyJSON { }
extension String: HandyJSON { }
extension Int: HandyJSON { }

enum UserDefaultsWrapperKey {
case base(String)
case handyJSON(String)
}

@propertyWrapper
struct UserDefaultsWrapper<T: HandyJSON> {
let key: UserDefaultsWrapperKey
let defaultValue: T
init(key: UserDefaultsWrapperKey, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}

var wrappedValue: T {
get {
switch key {
case .base(let keyString):
return UserDefaults.standard.value(forKey: keyString) as? T ?? defaultValue
case .handyJSON(let keyString):
if let string = UserDefaults.standard.value(forKey: keyString) as? String, let object = T.deserialize(from: string) {
return object
}
return defaultValue
}
}
set {
switch key {
case .base(let keyString):
UserDefaults.standard.set(newValue, forKey: keyString)
case .handyJSON(let keyString):
UserDefaults.standard.set(newValue.toJSONString() ?? "", forKey: keyString)
}
}
}
}

–EOF–