-
Notifications
You must be signed in to change notification settings - Fork 19
/
UserDefault.swift
55 lines (45 loc) · 1.3 KB
/
UserDefault.swift
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
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
* Copyright (c) 2011-2021, Zingaya, Inc. All rights reserved.
*/
import Foundation
fileprivate let userDefaults = UserDefaults(suiteName: "group.com.voximplant.flutterCallkit.example")
@propertyWrapper
struct UserDefault<T: Codable> {
private let key: String
private let defaultValue: T
init(_ key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
var wrappedValue: T {
get {
if let encodedValue = userDefaults?.object(forKey: key) as? Data,
let decodedValue = decode(encodedValue) {
return decodedValue
}
return defaultValue
}
set {
if let encodedValue = encode(newValue) {
userDefaults?.set(encodedValue, forKey: key)
}
}
}
private func encode(_ value: T) -> Data? {
try? JSONEncoder().encode(value)
}
private func decode(_ data: Data) -> T? {
try? JSONDecoder().decode(T.self, from: data)
}
}
@propertyWrapper
struct NullableUserDefault<T> {
private let key: String
init(_ key: String) {
self.key = key
}
var wrappedValue: T? {
get { userDefaults?.object(forKey: key) as? T }
set { userDefaults?.set(newValue, forKey: key) }
}
}