Generic Protocols in Swift

Joe Williams
7 min readMar 6, 2021

--

I’ve recently been undertaking a rebuild of my app, resulting in me thinking about what the architecture looks like as a whole. I’d previously made use of IGListKit, and over a couple of years it had served me well. Yet, with the advancements in modern collection views, I was able to rethink the use of this dependency. As a result, it led me down a bit of a rabbit hole into generics across protocols.

I wanted to solve the problem of declaring the same three things for a view controller. My app is made up of, pretty much, five controllers. Four these controllers are pretty much like-for-like clones. I declare a view model, a service, a data source, a loading view, and finally an error view:

class DiscoverController: UICollectionViewController {     lazy var dataSource: ....
lazy var errorView: ....
lazy var loadingView: ....
private let service: Service
private let viewModel: ViewModel
}class SearchController: UICollectionViewController { lazy var dataSource: ....
lazy var errorView: ....
lazy var loadingView: ....
private let service: Service
private let viewModel: ViewModel
}

I wanted to consolidate these into one, understandable, generic “List” controller. I’d done this to some extent before, but wanted to think a little bit more about responsibilities too. We’ll get into that a bit later on. For now, an overview.

Generics

The standard library is littered with generics, and you’ve likely use them more than you know. The guiding principle of generics is that they allow you to add flexibility and reusability to your code. Let’s review the following example:

class APIService {    func request(url: URL) -> AnyPublisher<Foo, Error> {
return URLSession.shared
.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: Foo.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
}

This might be okay in a number of scenarios. However, as the data you consume becomes more complex, you’re going to hit snags. Generics provide a concise way of…

--

--

Joe Williams

iOS Engineer @ Sky Betting & Gaming | Indie Dev @ Expodition Podcast App