5 Useful Swift Extensions to Use in Your iOS App
Make your development process a little bit faster
Today we will quickly explore some great Swift extensions that you can literally copy and paste into your app, and use to suit your needs.
The source code of all extensions is available at the bottom of the article.
Ever wanted to use hex instead of creating a long line of red, green, blue, and alpha combinations? This extension is here for the rescue:
Here is how we can use it (the code was run in an Xcode Playground):
We can play around with different hex colors using the great website https://flatuicolors.com/.
Have you ever needed to access the text field of your search bar? In iOS 13.0, we can directly access it like this:
However, if our users have lower iOS versions, the app will crash. We may obtain the text field using the following code:
It wouldn’t be very convenient if we had to write tedious
if else statements every time we need to access a text field, so we have the following great extension to handle this:
Now we can access the text field without worrying about the specific iOS version because everything is done behind the scenes:
Sometimes we want to display a one-tone placeholder for the
UIImageView, but we need to provide a specific asset for this. What if we could create an image using a specific color?
This extension allows us to create images with a
We sometimes need to display prices in our apps. But a value with no spaces (e.g., 235000) doesn’t look very nice, so we may want to insert a separator inside the number. This short extension allows us to do it very easily:
Let’s take a look at how we use it:
UITableViewCell and UICollectionViewCell
You don’t need to tell me how many times you have written this code:
We can see that we need to create a property
cellId and then pass it wherever it is needed. But how could make this code more succinct? Consider this protocol and extensions conforming to it:
Now we are able to access a
reuseIdentifier directly from the
The full source code of these extensions:
Interested in other ways you can shorten your Swift code and make it more efficient? Consider checking out my relevant articles that may be helpful for you:
When to Use the Comparable Protocol in Swift
This protocol is very handy for sorting your custom arrays
What is the CustomStringConvertible Protocol in Swift?
Spoiler: it makes debugging Swift objects much easier
What is OptionSet in Swift and When You Should Use It?
With a practical enumeration comparison
Thanks for reading!