Dependency Injection via Protocol Composition

Watching Stephen Celis’ “How to Control the World”, NSSpain 2018 presentation, one of the common Swift/iOS patterns he brings up caught my attention.

It’s this piece of code:

protocol APIClientProvider {
  var api: APIClientProtocol { get }
}

protocol DateProvider {
  func date() -> Date
}

extension World: APIClientProvider, DateProvider {}

class MyViewController: UIViewController {
  typealias Dependencies = APIClientProvider & DateProvider

  let label = UILabel()
  let dependencies: Dependencies

  init(dependencies: Dependencies) {
    self.dependencies = dependencies
  }

  func greet() {
    self.dependencies.api.fetchCurrentUser { result in
      if let user = result.success {
        self.label.text = "Hi, \(user.name)! It’s \(self.dependencies.date())."
      }
    }
  }
}

I never saw usage of a typealias Dependencies declaration that uses Protocol Composition to declare which dependencies are needed (expressed as 1 type being the combination of all actual dependencies).

This was news to me, so I wonder if you ran into something like this out there in the wild.

Hire me for freelance macOS/iOS work and consulting.

Buy my apps.

new posts via email.