Slide 1

Slide 1 text

Swift Generic Protocol 2017/12/6(ਫ) ΤϯδχΞษڧձ ઒ล ༟ଠ

Slide 2

Slide 2 text

͸͡Ίʹ ςʔϚ͕LTͰѻ͏ʹ͸ॏ͍ ͦͷׂʹࢿྉ͕ࡶ ໌Β͔ʹ༨ܭͳͱ͜Ζʹ࿑ྗΛׂ͍͍ͯΔ ͝ΊΜͶʂ

Slide 3

Slide 3 text

Ϟνϕʔγϣϯ Wireframe(Routerϓϩτίϧ)Λڞ௨Խ͍ͨ͠ ֤ContractʹҎԼͷΑ͏ͳίʔυ HogeViewͷ෦෼͸֤ViewΛฦ͍ͨ͠ protocol HogeWireframe: class { weak var view: HogeView? { get set } static func assembleModule() -> HogeView } Generics͡Όʂ

Slide 4

Slide 4 text

Genericͱ͍͑͹ class΍struct, funcʹtype parameterΛ͚ͭΔ class SomeClass { var someProperty: [T] = [] func someFunction(arg0: T, arg1: S) { print(arg0, arg1) } } let c = SomeClass() // func ͷ৔߹type parameterΛ໌ࣔ͠ͳ͍ c.someFunction(arg0: 0, arg1: "hello")

Slide 5

Slide 5 text

protocol΋ಉ༷ʹ…ʁ ͖ͬͱ͜Μͳײ͡Ͱ͠ΐʁ protocol SomeProtocol { var someProperty: [T] = [] func someFunction(arg0: T, arg1: S) } var p: SomeProtocol

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

classͷΑ͏ʹ͸Ͱ͖ͳ͍ protocolͷએݴʹtype parameter͸࢖͑ͳ͍ ͳΜͰ͔Α͘Θ͔Βͳ͍ Ͱ΋genericʹ͍ͨ͠͡ΌΜʁ

Slide 8

Slide 8 text

͡Ό͋Ͳ͏͢Μͷ͞ SelfΛ࢖͏ protocolʹద߹͢ΔΫϥεͳΒ͜ΕͰ associatedtypeΛ࢖͏ ͦͷଞͷΫϥε͸ͪ͜Β

Slide 9

Slide 9 text

Self ద߹͢ΔΫϥεʹͳΔ classͰ΋࢖͑Δ(ܧঝ͢Δͱ͖ͱ͔) protocol HasSelfProtocol { func returnSelf() -> Self } class AdoptHasSelfClass: HasSelfProtocol { func returnSelf() -> Self { return self } } var hasSelfProtocol: HasSelfProtocol = AdoptHasSelfClass()

Slide 10

Slide 10 text

associatedtype ೚ҙͷܕΛએݴͰ͖Δ protocol AssociatedTypeProtocol { associatedtype T var someProperty: T { set get } func someFunction() -> T } class AdoptAssociatedTypeClass: AssociatedTypeProtocol { typealias T = Int // ແͯ͘΋Α͍ var someProperty: Int = 0 func someFunction() -> Int { return someProperty } }

Slide 11

Slide 11 text

type parameterͱԿ͕ҧ͏ͷ͔ɾɾɾ

Slide 12

Slide 12 text

ͦΕ͸ͱ΋͔͘ Generic ProtocolΛ࡞Δ͜ͱ͕Ͱ͖ͨʂ ޙ͸͜ΕΛϓϩύςΟͷܕʹͯ͠ɾɾɾ var associatedTypeProtocol: AssociatedTypeProtocol = AdoptAssociatedTypeClass()

Slide 13

Slide 13 text

িܸͷ৽ࣄ࣮ Generic Protocol͸ϓϩύςΟͷܕʹͰ͖ͳ͍ ύϑΥʔϚϯεతͳཧ༝Ͱ͸(ਪଌ) https://qiita.com/omochimetaru/items/b41e7699ea25a324aefa ٕज़తʹͰ͖ͳ͍͜ͱ͸ͳ͍Β͍͠

Slide 14

Slide 14 text

Type Erasureͱ͍͏ղܾࡦ ϓϩτίϧΛ࣮ࡍͷܕʹద༻ struct AnyAssociatedType: AssociatedTypeProtocol { typealias T = A.T var someProperty: T private let _someFunction: () -> T func someFunction() -> T { return _someFunction() } init(_ inner: Inner) where T == Inner.T { self.someProperty = inner.someProperty self._someFunction = inner.someFunction } } var associatedTypeProtocol: AnyAssociatedType = AnyAssociatedType(AdoptAssociatedTypeClass())

Slide 15

Slide 15 text

݁ہͲ͏΍ͬͨͷʁ ͳΜ͔Ϋϥε࡞Γ·ͨ͠ protocol BaseViewWireframe: class { associatedtype SomeView: UIView weak var view: SomeView? { get set } static func assembleModule(vc: UIViewController) -> SomeView } class HogeWireframe: BaseViewWireframe { weak var view: HogeViewImpl? class func assembleModule(vc: UIViewController) -> HogeViewImpl { return HogeViewImpl() } }

Slide 16

Slide 16 text

·ͱΊ SwiftͷGeneric Protocol͸੍໿Ͱ࢖͍ʹ͍͘ type parameter͸࢖͑ͳ͍ ϓϩύςΟͷܕʹͰ͖ͳ͍ Type Erasureͱ͍͏Ṗͷղܾࡦ ͦΜͳʹίʔυ୹͘ͳΒͳͯ͘൵͍͠