Skip to content

Instantly share code, notes, and snippets.

@nrlnishan
Last active May 20, 2020 12:42
Show Gist options
  • Save nrlnishan/d441ce76a9737855e0339f8331584e86 to your computer and use it in GitHub Desktop.
Save nrlnishan/d441ce76a9737855e0339f8331584e86 to your computer and use it in GitHub Desktop.
Property Wrapper in Swift - Article
@propertyWrapper
struct Store {
// Key for UserDefaults
var key: String
// This is the special variable required in Property Wrapper.
var wrappedValue: Bool {
set { UserDefaults.standard.set(newValue, forKey: key) }
get { UserDefaults.standard.value(forKey: key) as? Bool ?? false }
}
init(key: String) {
self.key = key
}
}
// Now we can simplify our AppSettings struct as
struct AppSettings {
@Store(key: "is_dark_mode_enabled") static var isDarkModeEnabled: Bool
}
// value `true` is automatically stored in user defaults with key `is_dark_mode_enabled`
AppSettings.isDarkModeEnabled = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment