Useful Swift extensions #1

Speed up your development process and create cleaner code.

Eduardo Sanches Bocato
The Startup
2 min readMar 26, 2020

--

This time we will present some extensions that can simplify and speed up your development process. The code presented here can be used by copying and pasting it to your project.

1. NSError

Every time I have to create a simple NSError instance with just a description. I end up having to make a web search to remember which one is the key related to Localized Description.
After doing that lots of times, I've started using the extension below.

2. NSObject+ClassName

Aren't you tired of having to set the names of your cells, xibs and such with a raw string?

One of the advantages of using it is avoiding possible misspells and such.

3. Dequeuing TableViewCells

Every time we dequeue a UITableViewCell, we end up having to use an if-let, guard-let or a force-unwrap. To avoid doing that, I've been using the following extension.

Things like this:

Can turn into this:

Simply by using the extension below.

When the developer forgets to register the cell, the app crashes…
I think this is great, since it becomes very easy to find out what we forgot.

Note: The same extension can be applied to CollectionViewCells.

Bonus: Keyboard Control on Scrollviews

This is not an extension to a system class, but helps us enable a very common scenario that we have to deal on ScrollViews: making something follow the keyboard.

Usage: simply conform your view that has an ScrollView and setup the observers.

--

--

Eduardo Sanches Bocato
The Startup

iOS Engineer, AI enthusiast, Crossfit/Gymnastics. Currently working as iOS Lead @adidas