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_ :_
tableView.register(MyCell.self, forCellReuseIdentifier: “MyCell”)
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 :
protocol Reusable: class {
static var reuseIdentifier: String { get }
}
Then make your cell “Reusable” by implementing the protocol like so :
extension MyCell: Reusable {}
And here instead of implementing it, we are going to use Swift’s Protocol Extensions to provide a default value for all reusable objects !
extension Reusable {
static var reuseIdentifier: String {
return String(describing: Self.self)
}
}
By default reuseIdentifier will be the name of the class !
So you can now write :
tableView.register(MyCell.self, forCellReuseIdentifier: MyCell.reuseIdentifier)
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.
extension UITableView {
func register<T: UITableViewCell>(_: T.Type) where T: Reusable {
register(T.self, forCellReuseIdentifier: T.reuseIdentifier)
}
}
And now you can simply call :
tableView.register(Mycell.self)
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
Originally published here