---
title: "Combining protocols"
slug: combining-protocols
section: tech
date: 2016-09-28T10:53:00.000Z
canonical: https://roland.leth.ro/blog/tech/combining-protocols
---

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`:

```swift
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:

```swift
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:

```swift
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 [@roland.leth.ro](https://bsky.app/profile/roland.leth.ro), I'd love to chat about it.