Recently I was going through the motions of setting up a new UICollectionView . I had written a view model for my cells, and I had a UICollectionViewCell subclass all ready to go. All that was left to do was to implement cellForItem(at:) .

As an aside: if you’ve not worked with UICollectionView before, but are more of a UITableView kinda person, then you can just replace Collection with Table and Item with Row and this post should still be valid.

As a responsible iOS engineer [citation needed] I knew that the first thing I needed to do here was ask my collectionView to dequeue a cell. And to do that I had to call dequeueReusableCell(withReuseIdentifier:for:) , passing a String “reuse identifier.” In order for the collectionView to have any idea what I was talking about, I also had to call register(_:forCellWithReuseIdentifier:) on the collection, so it knew to map this reuse identifier to my UICollectionViewCell subclass.

That subclass looked roughly like this:

final class CustomCollectionViewCell: UICollectionViewCell { // code etc. }

Another aside: CustomCollectionViewCell is just an example name. Please never name classes like this.

I decided a sensible reuse identifier for this cell would be "CustomCollectionViewCell" . So I used that, and called both the methods. This is what those calls looked like:

// in a set up method

collectionView.register(

CustomCollectionViewCell.self,

forCellWithReuseIdentifier: "CustomCollectionViewCell"

) // in cellForItem(at:)

collectionView.dequeueReusableCell(

withReuseIdentifier: "CustomCollectionViewCell"

for: indexPath

)

This is obviously awful. We’ve got a magic string hanging around there, and it’s in more than one place. Clearly this is in need of some refactoring, so that’s exactly what I did. The first step was simply to move this string into a static constant on the CustomCollectionViewCell class.

final class CustomCollectionViewCell: UICollectionViewCell { static let reuseIdentifier = "CustomCollectionViewCell" }

Okay, good start. This means we can access the identifier anywhere in the code using CustomCollectionViewCell.reuseIdentifier . Already a massive improvement over what we had before. But it does present another problem. What if the class name changes later on?

We could just remember to change it, but let’s be real here: we’re humans, and we don’t always remember things like this. Even when it’s staring us right in the face. That’s why we get computers to do this stuff for us. So that leads nicely on to the next question: can we get the compiler to help us?

Well, if the answer was no, this would be an awfully short blog.

So how do we do it? See above, where we passed the reference to the CustomCollectionViewCell type into register(_:forCellWithReuseIdentifier:) ? Wouldn’t it be great if we could convert that type into a String somehow and just use that? That would be so great.

(Dramatic pause.)