Skip to content

Instantly share code, notes, and snippets.

@KaQuMiQ
Created October 23, 2019 07:10
Show Gist options
  • Save KaQuMiQ/441c7331f02d6150f9cf50a8e30c45cd to your computer and use it in GitHub Desktop.
Save KaQuMiQ/441c7331f02d6150f9cf50a8e30c45cd to your computer and use it in GitHub Desktop.
UserDefaults property wrapper
import Foundation
internal protocol AnyOptional {
var isNone: Bool { get }
}
extension Optional: AnyOptional {
var isNone: Bool {
switch self {
case .none: return true
case .some: return false
}
}
}
@propertyWrapper
internal final class UserDefaults<Wrapped> {
private let identifier: String
private let `default`: Wrapped
internal init(_ identifier: String, `default`: Wrapped) {
self.identifier = identifier
self.default = `default`
}
internal var wrappedValue: Wrapped {
get {
return UserDefaults.standard.object(forKey: identifier) as? Wrapped ?? `default`
}
set {
if (newValue as? AnyOptional)?.isNone ?? false {
UserDefaults.standard.removeObject(forKey: identifier)
} else {
UserDefaults.standard.set(newValue, forKey: identifier)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment