Cleaner code with swift extensions

Mohsin Khan
2 min readJan 18, 2021
Photo by Marc-Olivier Jodoin on Unsplash

Make your code reusable and more productive by utilizing complete power of swift extensions.

Swift has lot of great features and in my opinion one of the best is extension. Yes swift extension, this is really powerful and very useful feature in swift language as it allows you to add new methods to any existing class and you can call those methods without performing inheritance or overloading or overriding. As iOS developer while doing code reviews I have seen very often that people do code lot of duplication even for small small operation. Such as string to int conversion or date to string or vice versa or creating URLRequest objects etc.

In this post I will show you how we can utilize swift extension which can help you to avoid code duplication and we will get a precise, clean and easily maintainable code for our iOS app.

Now let's dive into the world of extension in swift. First we will see how to extend a class. We will take String class as an example.

import Foundationextension String {
func toInt() -> Int? {
return Int(self)
}
func anotherFunction() { //... }
}
And then for calling above function,And then for calling above function,var str = "1"print(str.toInt())orvar i = str.toInt()

It is as simple as that.

Now we will see a list of useful extension to speed up our iOS development.

String

Date

UIFont

Array

UIAlertController

UIImage

Bundle

UIApplication

NSNotification

UIView

Conclusion

So, I guess these are enough extension to inspire you and to give you an idea of how you can utilize swift’s extension in a proper way.

See you next time. Happy coding!

--

--

Mohsin Khan

Software Engineer by Profession, Gamer, Photographer, Bike Rider by Passion