Convenient Swift Extensions and Protocols

Photo by Mounzer Awad on Unsplash

Protocols and Extension are fantastic tools to help us be more productive.
I’m going to share a list of useful yet straightforward extensions and protocols that might help you organize your code and/or be more productive.

Bool Extension

We often want to toggle a bool and end up doing myBool = !myBool
This extension helps you avoid doing that.

Now you will only need to call myBool.toggle().

Optional Extension

Another annoying thing we have to deal with from time to time is using an optional Bool? in an if or any other control flow statements.
We sometimes end up using either a guard let or if let to unwrap it. This extension will help us avoid unwrapping and will default to false in case the bool is nil.

Now instead of unwrapping the boolean, you can use the unwrappedOrFalse property.

The same situation happens using other data types, especially when using Int (at least to me).

Now instead of unwrapping the value, you can use the unwrappedOrZero property.

You can even use this on custom objects like so:

Enums with rawValue is another data type that using this extension is really helpful.

And then you just need to call:

Cell Registrable Protocol

When working with UITableViewCell that needs to be added programmatically to the UITableView we usually create a UINib for each of the cells that we gonna register and end up using the plain string for the cell identifier.

Just make your UITableViewCell subclass conform to this protocol and this changes to this:

Now besides making the use of the reuse identifier type safe, your implementation changes to this:

Conclusion

Protocols and Extension in swift are compelling tools that we should use to avoid repeating yourself and to help us write more organized code.

Follow me

Twitter: dmlebron

iOS Engineer