Skip to content

Instantly share code, notes, and snippets.

@jaredh159
Created August 1, 2022 13:36
Show Gist options
  • Save jaredh159/5924d0a71742445ffd7ffcf06c8fbfc0 to your computer and use it in GitHub Desktop.
Save jaredh159/5924d0a71742445ffd7ffcf06c8fbfc0 to your computer and use it in GitHub Desktop.
user defaults backed property wrapper (credit: john sundell)
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