Swift Nifty TableViewCell Trick
Like every Swift developer out there I grew to love TableViewCells and Protocol Oriented Programming. Good because today’s is about a cool trick combining the two !
Let’s see the common way of registering a TableViewCell in Swift :
What bothers me first here is the error-prone string usage, then let’s be honest, 99% of the time, the cell identifier is just the string Cell class name. Maybe some of you see where I’m going with this :)
As always in Swift, start with a protocol :
Then make your cell “Reusable” by implementing the protocol like so :
And here instead of implementing it, we are going to use Swift’s Protocol Extensions to provide a default value for all reusable objects !
By default reuseIdentifier will be the name of the class !
So you can now write :
Okay we got rid of the error prone String, but wait we can do better than that can’t we?
Bonus
Surething! Let’s provide a shorter way to register Reusable cells.
Once again, protocols to the rescue!
Here we say, If you are a TableView registering a Reusable TableViewCell, then use cell’s reuseIdentifier by default.
And now you can simply call :
It’s as short as we can get I’m afraid 🎉🎉🎉
Wrap-up
Here we used Swift amazing protocol extensions to remove error-prone string identifier in a very common usage of TableViewCells.
We made the code both shorter and clearer while saving us from writing all of our UITableViewCells reuseIdentifiers by hand !
Remember, the best code is the one you don’t have to write :)
If you liked this trick you will probably love the iOS tools we make @freshos
If you like the article, Tap the 💚 below to spread this nifty trick