Last active
May 20, 2020 12:42
-
-
Save nrlnishan/d441ce76a9737855e0339f8331584e86 to your computer and use it in GitHub Desktop.
Property Wrapper in Swift - Article
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 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