Created
August 1, 2022 13:36
-
-
Save jaredh159/5924d0a71742445ffd7ffcf06c8fbfc0 to your computer and use it in GitHub Desktop.
user defaults backed property wrapper (credit: john sundell)
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
import Foundation | |
public protocol AnyOptional { | |
var isNil: Bool { get } | |
} | |
extension Optional: AnyOptional { | |
public var isNil: Bool { self == nil } | |
} | |
@propertyWrapper public struct UserDefaultsBacked<Value, Key: StorageKey> { | |
private let key: Key | |
private let defaultValue: Value | |
public init(wrappedValue defaultValue: Value, key: Key) { | |
self.defaultValue = defaultValue | |
self.key = key | |
} | |
public var wrappedValue: Value { | |
get { | |
UserDefaults.standard.value(forKey: key.string) as? Value ?? defaultValue | |
} | |
set { | |
if let optional = newValue as? AnyOptional, optional.isNil { | |
UserDefaults.standard.removeObject(forKey: key.string) | |
} else { | |
UserDefaults.standard.setValue(newValue, forKey: key.string) | |
} | |
} | |
} | |
} | |
public extension UserDefaultsBacked where Value: ExpressibleByNilLiteral { | |
init(key: Key) { | |
self.init(wrappedValue: nil, key: key) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment