-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStorage.swift
66 lines (53 loc) · 1.57 KB
/
Storage.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
//
// Storage.swift
//
// Created by Emad Bayramy on 1/20/20.
// Copyright © 2020 Emad Bayramy. All rights reserved.
//
import Foundation
@propertyWrapper
struct Storage<T: Codable> {
struct Wrapper<T>: Codable where T : Codable {
let wrapper: T
}
private let key: String
private let defaultValue: T
private let storage: UserDefaults = .standard
init(key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
var wrappedValue: T {
get {
// Read value from UserDefaults
guard let data = storage.object(forKey: key) as? Data else {
// Return defaultValue when no data in UserDefaults
return defaultValue
}
// Convert data to the desire data type
let value = try? JSONDecoder().decode(Wrapper<T>.self, from: data)
return value?.wrapper ?? defaultValue
}
set {
// Convert newValue to data
do {
let data = try JSONEncoder().encode(Wrapper(wrapper: newValue))
storage.set(data, forKey: key)
} catch {
storage.removeObject(forKey: key)
print(error)
}
}
}
}
extension Storage where T: ExpressibleByNilLiteral {
init(key: String) {
self.init(key: key, defaultValue: nil)
}
}
private protocol AnyOptional {
var isNil: Bool { get }
}
extension Optional: AnyOptional {
var isNil: Bool { self == nil }
}