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

Swift Generic Protocol

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

Swift Generic Protocol

Avatar for Yuta Kawabe

Yuta Kawabe

December 06, 2017
Tweet

More Decks by Yuta Kawabe

Other Decks in Programming

Transcript

  1. Genericͱ͍͑͹ class΍struct, funcʹtype parameterΛ͚ͭΔ class SomeClass<T: Int> { var someProperty:

    [T] = [] func someFunction<S>(arg0: T, arg1: S) { print(arg0, arg1) } } let c = SomeClass<Int>() // func ͷ৔߹type parameterΛ໌ࣔ͠ͳ͍ c.someFunction(arg0: 0, arg1: "hello")
  2. protocol΋ಉ༷ʹ…ʁ ͖ͬͱ͜Μͳײ͡Ͱ͠ΐʁ protocol SomeProtocol<T: Int> { var someProperty: [T] =

    [] func someFunction<S>(arg0: T, arg1: S) } var p: SomeProtocol<Int>
  3. Self ద߹͢ΔΫϥεʹͳΔ classͰ΋࢖͑Δ(ܧঝ͢Δͱ͖ͱ͔) protocol HasSelfProtocol { func returnSelf() -> Self

    } class AdoptHasSelfClass: HasSelfProtocol { func returnSelf() -> Self { return self } } var hasSelfProtocol: HasSelfProtocol = AdoptHasSelfClass()
  4. 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 } }
  5. Type Erasureͱ͍͏ղܾࡦ ϓϩτίϧΛ࣮ࡍͷܕʹద༻ struct AnyAssociatedType<A: AssociatedTypeProtocol>: AssociatedTypeProtocol { typealias T

    = A.T var someProperty: T private let _someFunction: () -> T func someFunction() -> T { return _someFunction() } init<Inner: AssociatedTypeProtocol>(_ inner: Inner) where T == Inner.T { self.someProperty = inner.someProperty self._someFunction = inner.someFunction } } var associatedTypeProtocol: AnyAssociatedType<AdoptAssociatedTypeClass> = AnyAssociatedType(AdoptAssociatedTypeClass())
  6. ݁ہͲ͏΍ͬͨͷʁ ͳΜ͔Ϋϥε࡞Γ·ͨ͠ 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() } }