Created
January 11, 2020 10:10
-
-
Save mrugeshtank/2d19cbce06e7383bd4cc0b809a04e7d1 to your computer and use it in GitHub Desktop.
This piece of code shows how much propertyWrapper can be useful
This file contains hidden or 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 MTUserDefaults { | |
@UserDefault("isOnBoardingCompleted", defaultValue: nil) | |
static var isOnBoardingCompleted: Bool? | |
} | |
// Usage | |
MTUserDefaults.isOnBoardingCompleted = true | |
print(MTUserDefaults.isOnBoardingCompleted) | |
// credit to https://www.avanderlee.com/swift/property-wrappers/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment