Skip to content

Instantly share code, notes, and snippets.

@AlonsoFloo
Created November 19, 2019 16:11
Show Gist options
  • Save AlonsoFloo/a70ef0ea369c31c3c753fa338368176c to your computer and use it in GitHub Desktop.
Save AlonsoFloo/a70ef0ea369c31c3c753fa338368176c to your computer and use it in GitHub Desktop.
Swift UserDefault property wrapper with @propertyWrapper, thanks to https://medium.com/@nimjea
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?
}
@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