Swift Extensions – speed up app development
Swift Extensions are quite a powerful feature and Swift and can greatly speed up your productivity. If you haven’t used them yet your in for a treat.
What are Swift extensions?
Extensions allow you to “extend” the functionality of an existing Swift class. It allows you to add custom methods to these classes which can then be called from anywhere in your code. Further details on what exactly extensions can do can be found in the Apple documentation.
Some examples of what Swift extensions can do are:
- Check if an email is valid
- Convert measurements between imperial and metrics
- Create custom UIColor’s
- And so on!
Creating and extension in Swift
We have created a new single view application in Swift. Then create three new Swift files and name them as follows:
- Int.swift
- UIColor.swift
- String.swift
Once done open up Int.swift – lets make our first extension:
First Swift Extension – doubling a number
Ok so let’s imagine we have to double numbers alot in our app. Coding it to double a number everywhere it needs to is highly inefficient and leads to code that is bad to maintain. In our Int.swift code the class as follows:
import Foundation extension Int { func double() -> Int { return self * 2 } }
To “extend” a class we use extension ClassName { … }. So in this case to extend the Int class we are using extension Int { … }. We can then add functions and variables to our extension in this class.
In this case we have added a double function, which it will take self (The current Int value), times it by two and return it. Lets go to the ViewController.swift to see it working, add the following lines of code to viewDidLoad():
var age = 21 age = age.double() print(age)
- First of all we declare age as 21, this gets set as an Int variable
- Next we set age to be double. This is our extension in action. Recall that in the above extension code we take self and double it. In this case self is 21 (The variable of age) and double it
- We then print out the new age to the console which results in 42
42
Nice – so we have created an extension in Swift. Now let’s see if we can improve on the extension we just created. What if we could take:
age = age.double()
and turn it into
age.double()
It would be alot neater right? Well we can if we change the Int.swift double extension to the following:
mutating func double() { self = self * 2 }
- Instead of returning and Int we set self to double itself
- We have to add mutating to the function name – this indicates that self will change during the function. Otherwise we cannot modify self in the function resulting in an error
Now in viewDidLoad lets change our code to double 21 to the following, as you can see it’s much neater now.
var age = 21 age.double() print(age)
Let’s take a look at some other extensions we can create and some quirks that we can avoid.
Custom UIColor extension
First lets take a look at UIColor and returning a custom color. Another great feature of extensions is we can create a custom initializer. For UIColor this allows us create a colour from a hex code which we look at in the tutorial here. In the meantime lets make our own custom color called seemuBlue – open up UIColor.swift and code it as follows, remember to import UIKit as it is needed for UIColor.
import UIKit extension UIColor { func seemuBlue() -> UIColor { return UIColor(colorLiteralRed: 0/255, green: 173/255, blue: 247/255, alpha: 1) } }
Now in viewDidLoad() we can set the background color of the app to be seemuBlue as follows:
self.view.backgroundColor = UIColor().seemuBlue()
You might notice this is a bit of a strange syntax to what you would usually set a color. E.g The default blue as follows dosen’t have the brackets () after UIColor, and the color().
self.view.backgroundColor = UIColor.blue
To get our custom seemuBlue color to follow this syntax (You can try and change it as is, but it is but will get an error!) we need to change our UIColor extension to match the following
import UIKit extension UIColor { open class var seemuBlue: UIColor { return UIColor.init(colorLiteralRed: 0/255, green: 173/255, blue: 247/255, alpha: 1) } }
By using a variable that is open class we can then set our custom background color as follows which is the same style as setting a default color:
self.view.backgroundColor = UIColor.seemuBlue
Validating an email extension
Finally the last extension we will look at is validating if a string is an email address. This is quite a straightforward one compared to the previous examples, open up String.swift and change the code to match the following extension:
import Foundation extension String { func isValidEmail() -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: self) } }
This uses a RegEx string to check if a string matches this format which is an email address and returns a boolean – true if it’s a valid email, false if not. You can verify this by going to the ViewController.swift and adding the following checks in viewDidLoad()
let email1 = "andrew@seemuapps.com" let email2 = "bob" print(email1.isValidEmail()) // Returns true print(email2.isValidEmail()) // Returns false
I will leave the code to you to run and verify the results as above!
As we can see from these three simple examples extensions in Swift can be very powerful – by extending classes with commonly used functions we can save time coding, it also results in easier to maintain code as the functions are in once place. So what ideas do you have for your own extensions now? Post below!