Combining protocols

:  ~ 2 min read

Let's say we have a controller that can fetch some data. What would this imply? A loading spinner, the fetching of the data and the update of the UI. We can create a protocol for this, maybe Fetchable:

protocol Fetchable {
  func showSpinner()
  func fetchData()
  func updateUI()
}
[...]
class Controller: UIViewController, Fetchable {
  // showSpinner, fetchData and updateUI are required
}

But showing a spinner and updating the UI could be useful by themselves, so we could extract those into separate protocols:

protocol Loadable {
  func showSpinner()
}

protocol Fetchable {
  func fetchData()
}

protocol UIUpdateable {
  func updateUI()
}
[...]
class Controller: UIViewController, Loadable, Fetchable, UIUpdateable { 
  // showSpinner, fetchData and updateUI are required
}

But instead of conforming to all three, we can declare Fetchable as conforming to the other two:

protocol Fetchable: Loadable, UIUpdateable {
  func fetchData()
}
[...]
// This is now the equivalent of the above, when we conformed to all three, individually.
class Controller: UIViewController, Fetchable {
  // showSpinner, fetchData and updateUI are required
}

The advantage is that we can now conform to each protocol individually, and when Fetchable is required, there's slightly less typing. As always, feel free to drop by @rolandleth, I'd love to chat about it.