-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathDefaults.swift
More file actions
188 lines (165 loc) · 6.49 KB
/
Copy pathDefaults.swift
File metadata and controls
188 lines (165 loc) · 6.49 KB
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
//
// Defaults.swift
//
// Copyright (c) 2017 - 2018 Nuno Manuel Dias
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
public class DefaultsKey {}
/// Represents a `Key` with an associated generic value type conforming to the
/// `Codable` protocol.
///
/// static let someKey = Key<ValueType>("someKey")
public final class Key<ValueType: Codable>: DefaultsKey {
fileprivate let _key: String
public init(_ key: String) {
_key = key
}
}
/// Provides strongly typed values associated with the lifetime
/// of an application. Apropriate for user preferences.
/// - Warning
/// These should not be used to store sensitive information that could compromise
/// the application or the user's security and privacy.
public final class Defaults {
private var userDefaults: UserDefaults
/// Shared instance of `Defaults`, used for ad-hoc access to the user's
/// defaults database throughout the app.
public static let shared = Defaults()
/// An instance of `Defaults` with the specified `UserDefaults` instance.
///
/// - Parameter userDefaults: The UserDefaults.
public init(userDefaults: UserDefaults = UserDefaults.standard) {
self.userDefaults = userDefaults
}
/// Deletes the value associated with the specified key, if any.
///
/// - Parameter key: The key.
public func clear<ValueType>(_ key: Key<ValueType>) {
userDefaults.set(nil, forKey: key._key)
userDefaults.synchronize()
}
/// Checks if there is a value associated with the specified key.
///
/// - Parameter key: The key to look for.
/// - Returns: A boolean value indicating if a value exists for the specified key.
public func has<ValueType>(_ key: Key<ValueType>) -> Bool {
return userDefaults.value(forKey: key._key) != nil
}
/// Returns the value associated with the specified key.
///
/// - Parameter key: The key.
/// - Returns: A `ValueType` or nil if the key was not found.
public func get<ValueType>(for key: Key<ValueType>) -> ValueType? {
if isSwiftCodableType(ValueType.self) || isFoundationCodableType(ValueType.self) {
return userDefaults.value(forKey: key._key) as? ValueType
}
guard let data = userDefaults.data(forKey: key._key) else {
return nil
}
do {
let decoder = JSONDecoder()
let decoded = try decoder.decode(ValueType.self, from: data)
return decoded
} catch {
#if DEBUG
print(error)
#endif
}
return nil
}
/// Sets a value associated with the specified key.
///
/// - Parameters:
/// - some: The value to set.
/// - key: The associated `Key<ValueType>`.
public func set<ValueType>(_ value: ValueType, for key: Key<ValueType>) {
if isSwiftCodableType(ValueType.self) || isFoundationCodableType(ValueType.self) {
userDefaults.set(value, forKey: key._key)
userDefaults.synchronize()
return
}
do {
let encoder = JSONEncoder()
let encoded = try encoder.encode(value)
userDefaults.set(encoded, forKey: key._key)
userDefaults.synchronize()
} catch {
#if DEBUG
print(error)
#endif
}
}
/// Removes given bundle's persistent domain
///
/// - Parameter type: Bundle.
public func removeAll(bundle : Bundle = Bundle.main) {
guard let name = bundle.bundleIdentifier else { return }
self.userDefaults.removePersistentDomain(forName: name)
}
/// Checks if the specified type is a Codable from the Swift standard library.
///
/// - Parameter type: The type.
/// - Returns: A boolean value.
private func isSwiftCodableType<ValueType>(_ type: ValueType.Type) -> Bool {
switch type {
case is String.Type, is Bool.Type, is Int.Type, is Float.Type, is Double.Type:
return true
default:
return false
}
}
/// Checks if the specified type is a Codable, from the Swift's core libraries
/// Foundation framework.
///
/// - Parameter type: The type.
/// - Returns: A boolean value.
private func isFoundationCodableType<ValueType>(_ type: ValueType.Type) -> Bool {
switch type {
case is Date.Type:
return true
default:
return false
}
}
}
// MARK: ValueType with RawRepresentable conformance
extension Defaults {
/// Returns the value associated with the specified key.
///
/// - Parameter key: The key.
/// - Returns: A `ValueType` or nil if the key was not found.
public func get<ValueType: RawRepresentable>(for key: Key<ValueType>) -> ValueType? where ValueType.RawValue: Codable {
let convertedKey = Key<ValueType.RawValue>(key._key)
if let raw = get(for: convertedKey) {
return ValueType(rawValue: raw)
}
return nil
}
/// Sets a value associated with the specified key.
///
/// - Parameters:
/// - some: The value to set.
/// - key: The associated `Key<ValueType>`.
public func set<ValueType: RawRepresentable>(_ value: ValueType, for key: Key<ValueType>) where ValueType.RawValue: Codable {
let convertedKey = Key<ValueType.RawValue>(key._key)
set(value.rawValue, for: convertedKey)
}
}