iOS — Refactoring in Swift: Identifiers!
Here are a few suggestions that might make your development process more efficient…
1. UITableViewCells
& UICollectionViewCells
identifiers:
This section covers reusable cell that needs an identifier to reuse and to register it the respective container view, that is, UITableView
or UICollectionView
UICollectionViewCell
for my example, it should apply the same way to UITableViewCell
) it looks something like this:Now we set the identifier in the attributes inspector. I strongly suggest to name it the same as the class name, you will see why in a moment.
Now, we update our custom cell class to include a static constant. That has the name identifier and stores our identifier which in this case is MyCell
. The line would look something like this… static let identifier = “MyCell”
. But if it’s the same as the class name then I think we can do something better. We can use the describing String initializer to get the name of the class… static let identifier = String(describing: MyCell.self)
If we make each custom cell’s identifier same as the class name then we can generalize this even further by extending the UICollectionViewCell
and UITableViewCell
classes!
After writing these extensions we no longer need to make a static variable in each and every custom class. Therefore, we can get rid of line static let identifier = String(describing: MyCell.self)
in our custom classes. Now we can simply get the identifier of the cell without looking all around our project like this:
I understand that there can be exceptions to naming the cell identifier same as the class name. Here is my solution to that exception, instead of making the identifier a static var
make it a class var
, this gives us the advantage to override the identifier variable in our custom cell class and assign a custom String. This adds one extra step but we still enjoy the benefit of autocomplete. The updated code would like this:
After these updates print(MyCell.identifier)
returns…
This method keeps the source code free of strings, helps the developer take advantage of autocomplete and is easy to maintain and update. Next up: Segue identifiers.