Skip to content

Instantly share code, notes, and snippets.

@nrlnishan
Last active May 20, 2020 12:44
Show Gist options
  • Save nrlnishan/521789ff602e3623eab553c4fef81505 to your computer and use it in GitHub Desktop.
Save nrlnishan/521789ff602e3623eab553c4fef81505 to your computer and use it in GitHub Desktop.
Property Wrapper in Swift
// We make our Property Wrapper Generic.
@propertyWrapper
struct Store<T> {
// This is the key that user can provide
var key: String
// The default value for the property
var defaultValue: T
// Now it returns Generic value instead of Bool
var wrappedValue: T {
set { UserDefaults.standard.set(newValue, forKey: key) }
get { UserDefaults.standard.value(forKey: key) as? T ?? defaultValue }
}
// We ask both key and default value during initialization.
init(key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
}
// Usage:
struct AppSettings {
@Store(key: "app_user_name", defaultValue: "") static var userName: String
@Store(key: "is_dark_mode_enabled", defaultValue: false) static var isDarkModeEnabled: Bool
}
AppSettings.userName = "Ironman"
AppSettings.isDarkModeEnabled = false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment