Created
July 24, 2019 02:39
-
-
Save yutailang0119/26183bef5e7c878d491fcb3d8540609f 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
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