Avatar
yutailang0119 7/24/2019 2:12 AM
これコンパイル通るし、bar はString?として扱えるのすごいな @propertyWrapper public struct UserDefault<Value> { private let key: String private let defaultValue: Value private let defaults: UserDefaults public init(key: String, defaultValue: Value, defaults: UserDefaults = .standard) { self.key = key self.defaultValue = defaultValue self.defaults = defaults } public 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 } (edited)