Upgrade to Pro — share decks privately, control downloads, hide ads and more …

20191206 Property Wrappers 入門

Kei Ito
December 06, 2019

20191206 Property Wrappers 入門

Kei Ito

December 06, 2019
Tweet

More Decks by Kei Ito

Other Decks in Programming

Transcript

  1. 4& IUUQTHJUIVCDPNBQQMFTXJGUFWPMVUJPOCMPCNBTUFS QSPQPTBMTQSPQFSUZXSBQQFSTNE There are property implementation patterns that come

    up repeatedly. Rather than hardcode a fixed set of patterns into the compiler (as we have done for lazy and @NSCopying), we should provide a general "property wrapper" mechanism to allow these patterns to be defined as libraries.
  2. struct Object { @LateInitialized var text: String } @propertyWrapper struct

    LateInitialized<T> { private var storage: T? var wrappedValue: T { get { guard let value = storage else { fatalError() } return value } set { storage = newValue } } }
  3. var obj1 = Object() print("\(obj1.text)") // -> fatal error var

    obj2 = Object() obj2.text = "hello" print("\(obj2.text)") // -> "hello"
  4. @propertyWrapper struct UserDefault<T> { let key: String let defaultValue: T

    var wrappedValue: T { get { return (UserDefaults.standard.object(forKey: key) as? T) ?? defaultValue } set { UserDefaults.standard.set(newValue, forKey: key) } } }
  5. @UserDefault(key: "initialized", defaultValue: false) var initialized: Bool @UserDefault(key: "username", defaultValue:

    "") var username: String obj.username = "mobile" print("\(UserDefaults.standard.string(forKey: "username")!)") // -> "mobile" UserDefaults.standard.set("act", forKey: "username") print("\(obj.username)") // -> "act"
  6. ॻ͖׵͑ϧʔϧ @propertyWrapper struct WrapperA<T> {} @propertyWrapper struct WrapperB<T> {} //

    ॳظ஋ @WrapperA var obj: String = "test" ɹ↓ private var _obj: WrapperA<String>(wrappedValue: "test") // ࿈݁Մೳ @WrapperA @WrapperB var obj: String ɹ↓ private var _obj: WrapperA<WrapperB<String>>