How to use Codable to store preferences in Swift

Issue #462

Using object, we don’t need to care about nil vs false like in UserDefaults, our object is the source of truth

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class StoringHandler<T: Codable> {
private let key: Storage.Keys
private let storage = Deps.storage

init(key: Storage.Keys) {
self.key = key
load()
}

var object: T? {
didSet {
if let object = object {
try? storage.save(object: object, key: key)
} else {
try? storage.clear(key: key)
}
}
}

private func load() {
self.object = try? storage.load(key: key, as: T.self)
}
}

Then subclass StoringHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct OnboardInfo: Codable {
let hasOnboarded: Bool
}

final class OnboardingHandler: StoringHandler<OnboardInfo> {
let storage = Deps.storage

var hasOnboarded: Bool {
get {
return object?.hasOnboarded ?? false
}
set {
object = OnboardInfo(hasOnboarded: newValue)
}
}
}

Comments