iOS Cell Registration & Reusing with Swift Protocol Extensions and Generics

Guille Gonzalez
Dec 31, 2015 · 2 min read

For a better reading experience, you can also find this post at

A common task when developing iOS apps is to register custom cell subclasses for both UITableView and UICollectionView. Well, that is if you don’t use Storyboards, of course.

Both UITableView and UICollectionView offer a similar API to register custom cell classes:

A widely accepted solution to handle cell registration and dequeuing is to declare a constant for the reuse identifier:

Let’s try to generalize this code and make it simpler and safe.

First of all, it would be nice to get away with declaring a constant for every reuse identifier in our app. We can just use the name of the custom cell class as a default reuse identifier.

We can create a protocol for Reusable Views and provide a default implementation constrained to UIView subclasses.

By making BookCell conform to the ReusableView protocol, we get a unique reuse identifier per cell subclass.

Next, we can get rid of the hard-coded string we are using to load the Nib.

Let’s create a protocol for Nib Loadable Views and provide a default implementation using protocol extensions.

By making our BookCell class conform to the NibLoadableView protocol we now have a safer way to get the Nib name.

If you use a different name for the XIB file than the one provided by Xcode, you can always override the default implementation of the nibName property.

With these two protocols in place, we can use Swift Generics and extend UICollectionView to simplify cell registration and dequeuing.

Notice that we created two versions of the register method, one for cell subclasses implementing just ReusableView and another one for cell subclasses implementing both ReusableView and NibLoadableView. This nicely decouples the view controller from the specific cell registration method.

Another nice detail is that the dequeueReusableCell method doesn’t need to take any reuse identifier and uses the cell subclass type for the return value.

Now the cell registration and dequeuing code looks much better :).


If you are coming from Objective-C it is worth to investigate powerful Swift features like Protocol Extensions and Generics to find alternate and more elegant ways to deal with Cocoa classes.

Here you can find the markdown version of this story.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store