Created
November 5, 2020 03:27
-
-
Save yoxisem544/bf7908357969637309f8552d52906d84 to your computer and use it in GitHub Desktop.
UserDefaults property wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public protocol AnyOptional { | |
var isNil: Bool { get } | |
} | |
extension Optional: AnyOptional { | |
public var isNil: Bool { self == nil } | |
} | |
@propertyWrapper | |
public struct DefaultsStorage<T> where T: Codable { | |
let key: String | |
let defaultValue: T | |
let userDefaults = UserDefaults.standard | |
init(_ key: String, defaultValue: T) { | |
self.key = key | |
self.defaultValue = defaultValue | |
} | |
public var wrappedValue: T { | |
get { | |
if let data = userDefaults.data(forKey: key) { | |
let value = try? JSONDecoder().decode(T.self, from: data) | |
return value ?? defaultValue | |
} else { | |
return defaultValue | |
} | |
} | |
set { | |
if let value = newValue as? AnyOptional, value.isNil { | |
userDefaults.removeObject(forKey: key) | |
} else { | |
let data = try? JSONEncoder().encode(newValue) | |
userDefaults.set(data, forKey: key) | |
} | |
} | |
} | |
} | |
// see more: https://swiftbysundell.com/articles/property-wrappers-in-swift/ | |
extension DefaultsStorage where T: ExpressibleByNilLiteral { | |
init(_ key: String) { | |
self.key = key | |
self.defaultValue = nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment