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

20191206 Property Wrappers 入門

70adfe7679427fa498899769e632b672?s=47 Kei Ito
December 06, 2019

20191206 Property Wrappers 入門

70adfe7679427fa498899769e632b672?s=128

Kei Ito

December 06, 2019
Tweet

Transcript

  1. 1SPQFSUZ8SBQQFST ೖ໳ .PCJMF"DU04"," JUPL!ͦΒ͔ͥ

  2. JUPL!ͦΒ͔ͥ w ͍ͱ͏͚͍ʢJUPLʣ w ɹɹɹɹɹɹͷதͷਓ w ϞόΠϧΞϓϦΤϯδχΞ݉$&0 w ෭ۀͰϑϦʔϥϯεత w

    IUUQTJUPLKQ IUUQTTPSBLB[FDPKQ !JUPLKQ
  3. ॴࡏ஍ɿژ౎ࢢதژ۠ ࣾһਓࣗ෼

  4. ࣮੷ डୗ ࣗࣾ

  5. .PEFSO4XJGU"1*%FTJHO IUUQTEFWFMPQFSBQQMFDPNWJEFPTQMBZXXED

  6. 1SPQFSUZ8SBQQFST

  7. final class UserData: ObservableObject { @Published var showFavoritesOnly = false

    @Published var landmarks = landmarkData } ͜Ε
  8. 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.
  9. Α͏͢Δʹ ϓϩύςΟʹର͢Δڞ௨ͷॲཧΛ ͖Ε͍ʹ·ͱΊͯ͠·͍·͠ΐ͏ ͱ͍͏ػೳ

  10. w 4XJGUҎ߱ w 4XJGUϥϯλΠϜͰ΋ಈ͖·͢ w J04Ͱ΋ಈ͖·͢

  11. ྫ ʮ஗ԆॳظԽʯ

  12. 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 } } }
  13. var obj1 = Object() print("\(obj1.text)") // -> fatal error var

    obj2 = Object() obj2.text = "hello" print("\(obj2.text)") // -> "hello"
  14. ྫ ʮ6TFS%FGBVMUTʯ

  15. @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) } } }
  16. @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"
  17. ΋͏গ͠ৄ͘͠

  18. ॻ͖׵͑ϧʔϧ @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>>
  19. ېࢭࣄ߲ w XSBQQFS͖ͭͷQSPQFSUZ͸ w QSPUPDPM಺Ͱ͸એݴͰ͖ͳ͍ w FYUFOTJPO಺Ͱ͸એݴͰ͖ͳ͍ w PWFSSJEFͰ͖ͳ͍ w

    TFUUFSHFUUFS͚ͭͯ͸͍͚ͳ͍ ͳͲ
  20. ࢀߟࢿྉ w IUUQTEFWFMPQFSBQQMFDPNWJEFPTQMBZ XXED w IUUQTHJUIVCDPNBQQMFTXJGUFWPMVUJPO CMPCNBTUFSQSPQPTBMTQSPQFSUZ XSBQQFSTNE