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

Dependency Injection in Swift - potatotips #27

Dependency Injection in Swift - potatotips #27

Presentation at potatotips #27 on March 16, 2016.
http://connpass.com/event/27156/

Yoichi Tagaya

March 16, 2016
Tweet

More Decks by Yoichi Tagaya

Other Decks in Programming

Transcript

  1. try! Swift Conference Day 3 http://niwatako.hatenablog.jp/entry/2016/03/04/182144 http://niwatako.hatenablog.jp/entry/2016/03/04/130940 Veronica Ray Ash

    Furrow Good to use DI Why Use Dependency Injection (DI) - Easy customization - Clear ownership - Testability http://www.tryswiftconf.com “ “
  2. Inversion of Control • I'm talking to you.
 / You're

    talking to me. • You call libraries.
 / Frameworks call you. • You create what you use.
 / What you use are created (and passed).
  3. Problem of Dependency Injection Much later... /FUXPSL $MBTT" 4FOTPS -PDBUJPO

    4USVDU# $MBTT$ Dependency 4USVDU& $MBTT% $MBTT' $MBTT( $MBTT) $MBTT* Hard to manage
  4. Solution: DI Container Dependency graph %*$POUBJOFS Register the graph Resolve

    when you need *OTUBODFPG $MBTT( /FUXPSL $MBTT" 4FOTPS -PDBUJPO 4USVDU# $MBTT$ 4USVDU& $MBTT% $MBTT' $MBTT( $MBTT) $MBTT*
  5. Usage of Swinject - DI Container protocol XType { }

    struct X: XType { } protocol YType { } class Y: YType { let x: XType init(x: XType) { self.x = x } } protocol ZType { } class Z: ZType { let y: YType init(y: YType) { self.y = y } } import Swinject let container = Container() container.register(XType.self) { _ in X() } container.register(YType.self) { r in Y(x: r.resolve(XType.self)!) } container.register(ZType.self) { r in Z(y: r.resolve(YType.self)!) } Registration: Resolution: let z = container.resolve(ZType)! Type definition: Y→X Z→Y X Automatically resolved: Z→Y→X X Y Z
  6. Summary • Dependency Injection is good for mocking and testing.

    • DI container is useful for dependency management. • Swinject is a DI container framework for Swift.
  7. Further Readings • Dependency Injection Framework for Swift - Swinjectͷ঺հ


    http://qiita.com/yoichitgy/items/ed8aac4d6f1e6666a4aa • Dependency Injection in Swift (Tokyo iOS Meetup)
 https://speakerdeck.com/yoichitgy/dependency-injection-in-swift • Unit Testing in Swift: Dependency Injection
 https://www.natashatherobot.com/unit-testing-swift-dependency-injection/ • DI in Scala: Cake Pattern pros & cons
 http://www.warski.org/blog/2011/04/di-in-scala-cake-pattern-pros-cons/ • You Used To Inject Me In Your Constructor (Reader Monad)
 https://speakerdeck.com/mathonsunday/you-used-to-inject-me-in-your-constructor