Making Use of Swift Extensions
If you are used to Swift, you probably don't need a definition or explanation for Swift Extensions. But for the sake of any newbies who might chance on this, Swift.org says Extensions add new functionality to an existing class, structure, enumeration, or protocol type… just like in the English language.
extension | ɪkˈstɛnʃ(ə)n, ɛkˈstɛnʃ(ə)n | noun
a part that is added to something to enlarge or prolong it: the railway’s southern extension.
There are many known benefits of Extensions. I’ll cover some below.
Extensions make your code cleaner.
Instead of having one class conform to 3 protocols in the same class. You can create the class and have two extensions of it. It makes your code cleaner and easy to debug.
Extensions make it easier to connect and debug dependencies
This one is quite important to me. Currently, to display images from URLs in my daily work, I use Nuke. The simplest form of using Nuke is…
Nuke.loadImage(with: url, into: imageView)
It looks pretty simple, right? Let’s say you call this simple line about 50 times in your codebase. Then, you decide not to go with Nuke again. You’ll rather go with Kingfisher. You have to go through all 50 parts of your code and switch to Kingfisher.
We can make this simpler by creating an extension of UIImageView. Then have a function where we set the URL in there. If you have to clean up, you just change the method.
extension UIImageView {
func setImage(imageURL: String){
self.kf.setImage(with: URL(string: imageURL)!)
}
}
to call this extension,
imageView.setImage(imageURL: "https://example.com/myImage.png")
TADAAA!!! If you decide not to use Kingfisher anymore, all you have to do is change the method in the extension and it reflects everywhere. You can use this format with almost all dependencies. That way it’s easier to keep it independent of 3rd party dependencies all the time.
The most common use of Extensions is to modify the parent class
The extension below just returns the squared result of the integer. Extensions like these are quite common.
extension Int {
var squared: Int {
return self * self
}
}
Nested Types — Another popular use of Extensions
Instead of having your UserDefault keys all over and forgetting about some of them, you can have an Extension of all your keys at one place and use them when you please.
extension UserDefaults {
enum Keys {
static let loginKey = "isLoggedIn"
static let shared = "userShared" }
}UserDefaults.standard.set(true, forKey: UserDefaults.Keys.loginKey)
Conclusion: Extensions make our jobs so much easier. SwifterSwift is a collection of extensions most people use. Check it out. Other related articles to check out include:
- UIView Extensions by Ankit Aggarwal
- Avoiding Extension Hell with Opt-in Extensions by Tjeerd in ‘t Veen