Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yutailang0119/26183bef5e7c878d491fcb3d8540609f to your computer and use it in GitHub Desktop.
Save yutailang0119/26183bef5e7c878d491fcb3d8540609f to your computer and use it in GitHub Desktop.
import Foundation
@propertyWrapper
struct UserDefault<Value> {
private let key: String
private let defaultValue: Value
private let defaults: UserDefaults
init(key: String, defaultValue: Value, defaults: UserDefaults = .standard) {
self.key = key
self.defaultValue = defaultValue
self.defaults = defaults
}
var wrappedValue: Value {
get {
(defaults.object(forKey: key) as? Value) ?? defaultValue
}
set {
defaults.set(newValue, forKey: key)
}
}
}
final class A {
@UserDefault(key: "foo", defaultValue: nil, defaults: .standard)
var foo: String?
@UserDefault(key: "bar", defaultValue: nil, defaults: .standard)
var bar: String
private func fooType() {
print(type(of: self.foo)) // Optional<String>
}
private func barType() {
print(type(of: self.bar)) // Optional<String>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment