Forked from 87kangsw/gist:fb44de10c42c51c87ad5b24b06a5ffdc
Created
August 11, 2021 09:40
-
-
Save dev-jason-hwkim/7337284c9b2312de20afa52d0c196509 to your computer and use it in GitHub Desktop.
UserDefaults PropertyWrapper
This file contains 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 | |
@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