Extensions in Swift with examples


In Swift, extensions can add new functionality to an existing class, structure, protocol or enumeration type without accessing the code of these types. It gives Apple developers the ability to extend the feature of those types without accessing the original source code.

While developing an app, developers often have to use different built-in data types that come with Xcode. We can not access the code of these types of data types. To extend the functionality for one of the types, the only option is to use the extension.

To declare an extension, we have to use the extension class in Swift:

extension Int {
    // Some new functionality
}

In the above snippet, I have shown a simple syntax for adding new functionality to the Integer data type.

Example of a Swift extension

Let’s see our very first example of creating an extension where we are going to add usable functionality to the integer data type. The extension is going to give the Int type data a feature to calculate the square root value.

Here is given our extension with the usage:

// Creating our extension for Int
extension Int {
    func getSquareValue() -> Int {
        let squareVal = self * self
        return squareVal
    }
}

// Using our extension
var myIntValue = 7
print( myIntValue.getSquareValue() )

Look at the above example carefully. You can notice have defined a method getSquareValue in the extension with the return type Int. Inside this function, we are calculating the square value of the integer that we have declared. The self keyword represents the integer value.

next, we created an integer type literal with the variable name myIntValue and assigned 7 to it. In the end, you can use the functionality from our extension in this way:

myIntValue.getSquareValue()

Using computed property in the extension

Swift doesn’t allow us to add stored properties in the extensions. To overcome this, you must use computed properties instead. Below is given an example:

// Creating an extension for Int
extension Int {
    var isEven: Bool {
        return self % 2 == 0
    }
}

// Using our extension
var myIntValue = 6
print(myIntValue.isEven)

Output:

true