Last active
March 16, 2022 10:55
-
-
Save AndreyAnt/cd6fd3a17e0b317013b5facec92fc3e9 to your computer and use it in GitHub Desktop.
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 public struct UserDefault<T> { | |
public let key: String | |
public let defaultValue: T | |
private let container: UserDefaults | |
public init(key: String, defaultValue: T, container: UserDefaults) { | |
self.key = key | |
self.defaultValue = defaultValue | |
self.container = container | |
} | |
public var wrappedValue: T { | |
get { | |
return container.object(forKey: key) as? T ?? defaultValue | |
} | |
set { | |
container.set(newValue, forKey: key) | |
} | |
} | |
} | |
class SomeClass<T> { | |
@UserDefault var someStoredValue: T | |
init(key: String, defaultValue: T, container: UserDefaults) { | |
self._someStoredValue = UserDefault(key: key, defaultValue: defaultValue, container: container) | |
} | |
} | |
let someClass = SomeClass(key: "secret-key", defaultValue: "1", container: .standard) | |
print(someClass.someStoredValue) | |
// prints "1" | |
let anotherClass = SomeClass(key: "secret-key", defaultValue: "2", container: .standard) | |
print(anotherClass.someStoredValue) | |
// prints "2" | |
someClass.someStoredValue = "hehe" | |
print(anotherClass.someStoredValue) | |
// prints "hehe" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment