Created
March 11, 2021 11:51
-
-
Save frzi/ed3d2cb43d6fdc6f1fabb6fa49bfd40c to your computer and use it in GitHub Desktop.
UserDefault property wrapper
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
/// Example of usage: | |
/// ```swift | |
/// @UserDefault("username") var username: String? = nil | |
/// @UserDefault("maxItems") var maxItems = 100 | |
/// ``` | |
@propertyWrapper | |
struct UserDefault<T> { | |
let defaultValue: T | |
let key: String | |
private let environment: UserDefaults | |
var wrappedValue: T { | |
get { | |
environment.object(forKey: key) as? T ?? defaultValue | |
} | |
set { | |
if case Optional<T>.none = newValue as Any { | |
environment.removeObject(forKey: key) | |
} | |
else { | |
environment.set(newValue, forKey: key) | |
} | |
} | |
} | |
init(wrappedValue: T, _ key: String, environment: UserDefaults = .standard) { | |
self.key = key | |
self.environment = environment | |
self.defaultValue = wrappedValue | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment