Created
November 19, 2019 16:11
-
-
Save AlonsoFloo/a70ef0ea369c31c3c753fa338368176c to your computer and use it in GitHub Desktop.
Swift UserDefault property wrapper with @propertyWrapper, thanks to https://medium.com/@nimjea
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
class Settings { | |
static let shared: Settings = { | |
Settings() | |
}() | |
private init() { | |
// Private, due to singleton | |
} | |
@UserDefaultProperty("on_off", defaultValue: false) | |
var isEnabled: Bool | |
@UserDefaultProperty("number", defaultValue: 3) | |
var number: Int | |
@UserDefaultProperty("name", defaultValue: nil) | |
var name: String? | |
} |
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
@propertyWrapper | |
struct UserDefaultProperty<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 { | |
UserDefaults.standard.set(newValue, forKey: key) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment