Extensions in Swift are very useful and super powerful which can help us organize our codes better, and increase maintainability and readability of your codes.
A very interesting point of Extensions is that you can write extensions for class, struct, protocol, or enum even you don’t have access to them.
In this tutorial, I explain some functionality of extension in Swift, but let’s take a look at the definition of extension in Swift documentation:
Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling).
Extensions in Swift can:
- Add computed instance properties and computed type properties
- Define instance methods and type methods
- Provide new initializers
- Define subscripts
- Define and use new nested types
- Make an existing type conform to a protocol
Extension Syntax
extension SomeType { // new functionality to add to SomeType goes here }
Ok, let’s write some examples:
extension Array where Element == String { func alphabeticallySort() -> Array { return self.sorted { $0.lowercased() < $1.lowercased() } } }
With this extension, we add alphabeticallySort() method to the Array class to sort arrays alphabetically.
extension Int { func percentOf(_ value: Int) -> Double { guard value >= 0 else { print("wrong percentage number...") return -1 } return (Double(self * value) / 100) } } 3.percentOf(10) // output = 0.3
With this extension, we add percentOf(_ value: Int) method to the Int class to calculate the percent of the number with the value percentage. As you can see, percentOf is a Swift function and we can add parameters to it.
Computed properties
Swift doesn’t let us add stored properties in extensions, so we must use computed properties instead.
In this example, I add isOdd property to Int class that returns true if the number is odd:
extension Int { var isOdd : Bool { return self % 2 != 0 } } 3.isOdd // output = true
Increase controllers readability:
The most useful application of extensions in Swift which I use in my projects is the ability to separate codes of controllers.
We all met massive controllers in our projects, especially in big projects.
One way that we can increase the readability of controller’s codes is using extensions.
For example, we can separate protocols of UITableView from the base class, like this:
class DetaiViewController: UIViewController { } // TableView DataSource extension DetaiViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { } }
Or we can separate relative methods which we use in controllers:
// MARK: - Setup View extension DetaiViewController { private func setupUI() { } } // MARK: - Calculate Score extension DetaiViewController { private func calculateScore() { } private func convertScoresToGift() { } }
You can read more about extensions in Swift Documentation