Last active
October 19, 2019 06:32
-
-
Save LukeSmith16/02780fbc5d66e59818271a658efa0d4f to your computer and use it in GitHub Desktop.
A good example of how we can use property wrappers in Swift 5 to make working with UserDefaults so much more cleaner. We can define a 'UserDefaultsConfig' type to contain all the values we want to persist making it easier to read!
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 UserDefault<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) | |
} | |
} | |
} | |
struct UserDefaultsConfig { | |
@UserDefault("has_onboarded", defaultValue: false) | |
static var userHasOnboarded: Bool | |
@UserDefault("app_theme", defaultValue: "main_theme") | |
static var appTheme: String | |
} | |
UserDefaultsConfig.userHasOnboarded = false | |
print(UserDefaultsConfig.userHasOnboarded) // Prints: false | |
UserDefaultsConfig.appTheme = "pro_theme" | |
print(UserDefaultsConfig.appTheme) // Prints: "pro_theme" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment