Cleaning Up CollectionViews and TableViews using Enums

Joe Spadafora
swiftjoe
Published in
2 min readJan 30, 2017

UITableViews and UICollectionViews can very easily get out of hand. Especially if you have a table where you need to display different types of items in different sections.

Let’s imagine an app where there are 4 sections in a tableview. The first section, section 0, might be one that displays an error banner on top of the collection if there is some sort of issue (Wifi being off, no bluetooth, etc.). Section 1 would contain a list of friends you’ve already connected with. Section 2 contains a list of friends that have sent invitations to you. Section 3 contains a cell that shows a background image if there is nothing in section 1 or 2, letting you know that you should pull to refresh.

Setting up the different sections might look something like this:

So, you’ve done the same thing throughout the rest of your controller, and everything works fine. Then, a day later, after setting up different cell sizes, logic and handling, the UX designers on your team decide that the invitations should be ON TOP of the friends.

So…you go through all of the 800 different delegate methods to fix it, changing lots of code…And you’ve now wasted an hour or so rewriting everything to work.

Is there a better way? Yes. It’s a simple solution with Enums and a simple extension on Int. First, make an enum with all the different sections of your table. This will allow you to do two great things: Use switch statements to make sure that you are covering all your cases, and abstract away the number of each section.

Adding the extension to Int is just some syntactic sugar.

With this now added, you can see the code is now more readable, cleaner, and easier to understand.

Now, the real beauty of this, is that to change the order of the sections, the only thing you have to do is switch the order of the cases in your enumeration. What was once a tedious task to go through and modify all of the existing code for the delegate methods is fixed in the blink of an eye.

Hopefully this cool trick helped you!

--

--