Skip to content

Instantly share code, notes, and snippets.

@AndreyAnt
Last active March 16, 2022 10:55
Show Gist options
  • Save AndreyAnt/cd6fd3a17e0b317013b5facec92fc3e9 to your computer and use it in GitHub Desktop.
Save AndreyAnt/cd6fd3a17e0b317013b5facec92fc3e9 to your computer and use it in GitHub Desktop.
@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