Using Type Markers for 'is' Type Predicates to Cover Generic Types

Maybe you have some old code (you wouldn’t write this nowadays, of course) that uses someValue is SomeType checks. Maybe you need to check if someValue is a generic type, like the following Box: Then your is predicates won’t work: The good news is that since you treat the concrete type as a mere marker, you can express this condition with a type marker protocol:

Continue reading …

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.

Implementing CollectionType in Swift 2.x

I ran into trouble with custom collections the other day and wondered how to reliably find out what the bare minimum for a custom CollectionType is. The compiler will only help a bit: It’s conforming to neither CollectionType nor SequenceType. Now I know SequenceType requires the generate() method – but don’t let this fool you. CollectionType will provide that for you if you meet its requirements.

Continue reading …