Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dev-jason-hwkim/7337284c9b2312de20afa52d0c196509 to your computer and use it in GitHub Desktop.
Save dev-jason-hwkim/7337284c9b2312de20afa52d0c196509 to your computer and use it in GitHub Desktop.
UserDefaults PropertyWrapper
import Foundation
@propertyWrapper struct UserDefaultsWrapper<T> {
let key: String
let defaultValue: T?
init(_ key: String, defaultValue: T?) {
self.key = key
self.defaultValue = defaultValue
}
var wrappedValue: T? {
get {
return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
}
set {
if let value = newValue as? OptionalProtocol, value.isNil() {
UserDefaults.standard.removeObject(forKey: key)
} else {
UserDefaults.standard.set(newValue, forKey: key)
}
}
}
}
fileprivate protocol OptionalProtocol {
func isNil() -> Bool
}
extension Optional: OptionalProtocol {
func isNil() -> Bool {
return self == nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment