|
| 1 | +// |
| 2 | +// Defaults.swift |
| 3 | +// |
| 4 | +// Copyright (c) 2017 - 204 Nuno Manuel Dias |
| 5 | +// |
| 6 | +// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | +// of this software and associated documentation files (the "Software"), to deal |
| 8 | +// in the Software without restriction, including without limitation the rights |
| 9 | +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | +// copies of the Software, and to permit persons to whom the Software is |
| 11 | +// furnished to do so, subject to the following conditions: |
| 12 | +// |
| 13 | +// The above copyright notice and this permission notice shall be included in all |
| 14 | +// copies or substantial portions of the Software. |
| 15 | +// |
| 16 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 | +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 | +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 | +// SOFTWARE. |
| 23 | +// |
| 24 | + |
| 25 | +import Foundation |
| 26 | + |
| 27 | +public protocol DefaultsKey {} |
| 28 | + |
| 29 | +/// Represents a `Key` with an associated generic value type conforming to the |
| 30 | +/// `Codable` protocol. |
| 31 | +/// |
| 32 | +/// static let someKey = Key<ValueType>("someKey") |
| 33 | +public struct Key<ValueType: Codable>: DefaultsKey { |
| 34 | + fileprivate let _key: String |
| 35 | + public init(_ key: String) { |
| 36 | + _key = key |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +/// Provides strongly typed values associated with the lifetime |
| 41 | +/// of an application. Apropriate for user preferences. |
| 42 | +/// - Warning |
| 43 | +/// These should not be used to store sensitive information that could compromise |
| 44 | +/// the application or the user's security and privacy. |
| 45 | +public struct Defaults { |
| 46 | + private var userDefaults: UserDefaults |
| 47 | + |
| 48 | + /// Shared instance of `Defaults`, used for ad-hoc access to the user's |
| 49 | + /// defaults database throughout the app. |
| 50 | + public nonisolated(unsafe) static let shared = Defaults() |
| 51 | + |
| 52 | + /// An instance of `Defaults` with the specified `UserDefaults` instance. |
| 53 | + /// |
| 54 | + /// - Parameter userDefaults: The UserDefaults. |
| 55 | + public init(userDefaults: UserDefaults = UserDefaults.standard) { |
| 56 | + self.userDefaults = userDefaults |
| 57 | + } |
| 58 | + |
| 59 | + /// Deletes the value associated with the specified key, if any. |
| 60 | + /// |
| 61 | + /// - Parameter key: The key. |
| 62 | + public func clear<ValueType>(_ key: Key<ValueType>) { |
| 63 | + userDefaults.set(nil, forKey: key._key) |
| 64 | + userDefaults.synchronize() |
| 65 | + } |
| 66 | + |
| 67 | + /// Checks if there is a value associated with the specified key. |
| 68 | + /// |
| 69 | + /// - Parameter key: The key to look for. |
| 70 | + /// - Returns: A boolean value indicating if a value exists for the specified key. |
| 71 | + public func has<ValueType>(_ key: Key<ValueType>) -> Bool { |
| 72 | + return userDefaults.value(forKey: key._key) != nil |
| 73 | + } |
| 74 | + |
| 75 | + /// Returns the value associated with the specified key. |
| 76 | + /// |
| 77 | + /// - Parameter key: The key. |
| 78 | + /// - Returns: A `ValueType` or nil if the key was not found. |
| 79 | + public func get<ValueType>(for key: Key<ValueType>) -> ValueType? { |
| 80 | + if isSwiftCodableType(ValueType.self) || isFoundationCodableType(ValueType.self) { |
| 81 | + return userDefaults.value(forKey: key._key) as? ValueType |
| 82 | + } |
| 83 | + |
| 84 | + guard let data = userDefaults.data(forKey: key._key) else { |
| 85 | + return nil |
| 86 | + } |
| 87 | + |
| 88 | + do { |
| 89 | + let decoder = JSONDecoder() |
| 90 | + let decoded = try decoder.decode(ValueType.self, from: data) |
| 91 | + return decoded |
| 92 | + } catch { |
| 93 | + #if DEBUG |
| 94 | + print(error) |
| 95 | + #endif |
| 96 | + } |
| 97 | + |
| 98 | + return nil |
| 99 | + } |
| 100 | + |
| 101 | + /// Sets a value associated with the specified key. |
| 102 | + /// |
| 103 | + /// - Parameters: |
| 104 | + /// - some: The value to set. |
| 105 | + /// - key: The associated `Key<ValueType>`. |
| 106 | + public func set<ValueType>(_ value: ValueType, for key: Key<ValueType>) { |
| 107 | + if isSwiftCodableType(ValueType.self) || isFoundationCodableType(ValueType.self) { |
| 108 | + userDefaults.set(value, forKey: key._key) |
| 109 | + return |
| 110 | + } |
| 111 | + |
| 112 | + do { |
| 113 | + let encoder = JSONEncoder() |
| 114 | + let encoded = try encoder.encode(value) |
| 115 | + userDefaults.set(encoded, forKey: key._key) |
| 116 | + userDefaults.synchronize() |
| 117 | + } catch { |
| 118 | + #if DEBUG |
| 119 | + print(error) |
| 120 | + #endif |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + // MARK: - RawRepresentable |
| 125 | + |
| 126 | + /// Returns the value associated with the specified key. |
| 127 | + /// |
| 128 | + /// - Parameter key: The key. |
| 129 | + /// - Returns: A `ValueType` or nil if the key was not found. |
| 130 | + public func get<ValueType: RawRepresentable>(for key: Key<ValueType>) -> ValueType? where ValueType.RawValue: Codable { |
| 131 | + let convertedKey = Key<ValueType.RawValue>(key._key) |
| 132 | + if let raw = get(for: convertedKey) { |
| 133 | + return ValueType(rawValue: raw) |
| 134 | + } |
| 135 | + return nil |
| 136 | + } |
| 137 | + |
| 138 | + /// Sets a value associated with the specified key. |
| 139 | + /// |
| 140 | + /// - Parameters: |
| 141 | + /// - some: The value to set. |
| 142 | + /// - key: The associated `Key<ValueType>`. |
| 143 | + public func set<ValueType: RawRepresentable>(_ value: ValueType, for key: Key<ValueType>) where ValueType.RawValue: Codable { |
| 144 | + let convertedKey = Key<ValueType.RawValue>(key._key) |
| 145 | + set(value.rawValue, for: convertedKey) |
| 146 | + } |
| 147 | + |
| 148 | + /// Removes given bundle's persistent domain |
| 149 | + /// |
| 150 | + /// - Parameter type: Bundle. |
| 151 | + public func removeAll(bundle: Bundle = Bundle.main) { |
| 152 | + guard let name = bundle.bundleIdentifier else { return } |
| 153 | + userDefaults.removePersistentDomain(forName: name) |
| 154 | + } |
| 155 | + |
| 156 | + /// Checks if the specified type is a Codable from the Swift standard library. |
| 157 | + /// |
| 158 | + /// - Parameter type: The type. |
| 159 | + /// - Returns: A boolean value. |
| 160 | + private func isSwiftCodableType<ValueType>(_ type: ValueType.Type) -> Bool { |
| 161 | + switch type { |
| 162 | + case is String.Type, is Bool.Type, is Int.Type, is Float.Type, is Double.Type: |
| 163 | + return true |
| 164 | + default: |
| 165 | + return false |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + /// Checks if the specified type is a Codable, from the Swift's core libraries |
| 170 | + /// Foundation framework. |
| 171 | + /// |
| 172 | + /// - Parameter type: The type. |
| 173 | + /// - Returns: A boolean value. |
| 174 | + private func isFoundationCodableType<ValueType>(_ type: ValueType.Type) -> Bool { |
| 175 | + switch type { |
| 176 | + case is Date.Type: |
| 177 | + return true |
| 178 | + default: |
| 179 | + return false |
| 180 | + } |
| 181 | + } |
| 182 | +} |
0 commit comments