-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
AppStorageKey.swift
433 lines (388 loc) · 15.8 KB
/
AppStorageKey.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#if canImport(Perception)
import Foundation
extension PersistenceKey {
/// Creates a persistence key for sharing data in user defaults given a key path.
///
/// For example, one could initialize a key with the date and time at which the application was
/// most recently launched, and access this date from anywhere using the ``Shared`` property
/// wrapper:
///
/// ```swift
/// @Shared(.inMemory("appLaunchedAt")) var appLaunchedAt = Date()
/// ```
///
/// - Parameter key: A string key identifying a value to share in memory.
/// - Returns: A persistence key.
public static func appStorage<Value>(
_ keyPath: ReferenceWritableKeyPath<UserDefaults, Value>
) -> Self where Self == AppStorageKey<Value> {
AppStorageKey(keyPath)
}
/// Creates a persistence key that can read and write to a boolean user default.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<Bool> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to an integer user default.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<Int> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to a double user default.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<Double> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to a string user default.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<String> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to a URL user default.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<URL> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to a user default as data.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<Data> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to an integer user default, transforming
/// that to a `RawRepresentable` data type.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage<Value: RawRepresentable>(_ key: String) -> Self
where Value.RawValue == Int, Self == AppStorageKey<Value> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to a string user default, transforming
/// that to a `RawRepresentable` data type.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage<Value: RawRepresentable>(_ key: String) -> Self
where Value.RawValue == String, Self == AppStorageKey<Value> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to an optional boolean user default.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<Bool?> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to an optional integer user default.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<Int?> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to an optional double user default.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<Double?> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to an optional string user default.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<String?> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to an optional URL user default.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<URL?> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to a user default as optional data.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage(_ key: String) -> Self
where Self == AppStorageKey<Data?> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to an optional integer user default,
/// transforming that to a `RawRepresentable` data type.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage<Value: RawRepresentable>(_ key: String) -> Self
where Value.RawValue == Int, Self == AppStorageKey<Value?> {
AppStorageKey(key)
}
/// Creates a persistence key that can read and write to an optional string user default,
/// transforming that to a `RawRepresentable` data type.
///
/// - Parameter key: The key to read and write the value to in the user defaults store.
/// - Returns: A user defaults persistence key.
public static func appStorage<Value: RawRepresentable>(_ key: String) -> Self
where Value.RawValue == String, Self == AppStorageKey<Value?> {
AppStorageKey(key)
}
}
/// A type defining a user defaults persistence strategy
///
/// See ``PersistenceKey/appStorage(_:)-9zd2f`` to create values of this type.
public struct AppStorageKey<Value> {
private let _load: () -> Value?
private let _save: (Value) -> Void
private let key: Key
private let store: UserDefaults
private enum Key: Hashable {
case string(String)
case keyPath(ReferenceWritableKeyPath<UserDefaults, Value>)
}
public init(_ keyPath: ReferenceWritableKeyPath<UserDefaults, Value>) {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store[keyPath: keyPath] }
self._save = { [store] in store[keyPath: keyPath] = $0 }
self.key = .keyPath(keyPath)
self.store = store
}
public init(_ key: String) where Value == Bool {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String) where Value == Int {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String) where Value == Double {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String) where Value == String {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String) where Value == URL {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String) where Value == Data {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String)
where Value: RawRepresentable, Value.RawValue == Int {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in
(store.object(forKey: key) as? Value.RawValue).flatMap(Value.init(rawValue:))
}
self._save = { [store] in store.set($0.rawValue, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String)
where Value: RawRepresentable, Value.RawValue == String {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in
(store.object(forKey: key) as? Value.RawValue).flatMap(Value.init(rawValue:))
}
self._save = { [store] in store.set($0.rawValue, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String) where Value == Bool? {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0 ?? nil, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String) where Value == Int? {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0 ?? nil, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String) where Value == Double? {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0 ?? nil, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String) where Value == String? {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0 ?? nil, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String) where Value == URL? {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0 ?? nil, forKey: key) }
self.key = .string(key)
self.store = store
}
public init(_ key: String) where Value == Data? {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in store.object(forKey: key) as? Value }
self._save = { [store] in store.set($0 ?? nil, forKey: key) }
self.key = .string(key)
self.store = store
}
public init<R: RawRepresentable>(_ key: String)
where R.RawValue == Int, Value == R? {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in
(store.object(forKey: key) as? R.RawValue).flatMap(R.init(rawValue:))
}
self._save = { [store] in store.set($0?.rawValue, forKey: key) }
self.key = .string(key)
self.store = store
}
public init<R: RawRepresentable>(_ key: String)
where R.RawValue == String, Value == R? {
@Dependency(\.defaultAppStorage) var store
self._load = { [store] in
(store.object(forKey: key) as? R.RawValue).flatMap(R.init(rawValue:))
}
self._save = { [store] in store.set($0?.rawValue, forKey: key) }
self.key = .string(key)
self.store = store
}
}
extension AppStorageKey: PersistenceKey {
public func load(initialValue: Value?) -> Value? {
if let initialValue, case let .string(key) = self.key {
self.store.register(defaults: [key: initialValue])
}
return self._load() ?? initialValue
}
public func save(_ value: Value) {
SharedAppStorageLocals.$isSetting.withValue(true) {
self._save(value)
}
}
public func subscribe(
initialValue: Value?, didSet: @escaping (_ newValue: Value?) -> Void
) -> Shared<Value>.Subscription {
switch self.key {
case let .keyPath(key):
let observer = self.store.observe(key, options: .new) { _, change in
guard
!SharedAppStorageLocals.isSetting
else { return }
didSet(change.newValue ?? initialValue)
}
return Shared.Subscription {
observer.invalidate()
}
case let .string(key):
let observer = Observer { value in
guard
!SharedAppStorageLocals.isSetting
else { return }
didSet(value ?? initialValue)
}
self.store.addObserver(observer, forKeyPath: key, options: .new, context: nil)
return Shared.Subscription {
self.store.removeObserver(observer, forKeyPath: key)
}
}
}
private class Observer: NSObject {
let didChange: (Value?) -> Void
init(didChange: @escaping (Value?) -> Void) {
self.didChange = didChange
super.init()
}
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?
) {
self.didChange(change?[.newKey] as? Value)
}
}
}
extension AppStorageKey: Hashable {
public static func == (lhs: AppStorageKey, rhs: AppStorageKey) -> Bool {
lhs.key == rhs.key && lhs.store == rhs.store
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self.key)
hasher.combine(self.store)
}
}
extension DependencyValues {
public var defaultAppStorage: UserDefaults {
get { self[DefaultAppStorageKey.self].value }
set { self[DefaultAppStorageKey.self].value = newValue }
}
}
private enum DefaultAppStorageKey: DependencyKey {
static var testValue: UncheckedSendable<UserDefaults> {
UncheckedSendable(
UserDefaults(
suiteName:
"\(NSTemporaryDirectory())co.pointfree.ComposableArchitecture.\(UUID().uuidString)"
)!
)
}
static var previewValue: UncheckedSendable<UserDefaults> {
Self.testValue
}
static var liveValue: UncheckedSendable<UserDefaults> {
UncheckedSendable(UserDefaults.standard)
}
}
// NB: This is mainly used for tests, where observer notifications can bleed across cases.
private enum SharedAppStorageLocals {
@TaskLocal static var isSetting = false
}
#endif