How to use Swift Extensions – XSTutorials

How to use Swift Extensions

With a Swift extension, you can add new functionality to an existing Swift file. You can literally add on new functions to an existing class, even if you don’t have access to the original source code of that class.

Lets’ take a look at this example:

extension UIViewController {
    func printSomething(_ message:String) {
        print(message)
    }
}

The above extension has been declared after the Class closure – extensions cannot reside inside a Class or a function, they are independent. You can call the function of that extension in any function of your Class, lets’ say inside the viewDidLoad() one, like this:

printSomething("Hey, this extension works!")

The great thing about extensions is that, once they have been instantiated in a single Swift file, they can be called from any other file.

The extension we shown in the example above is a UIViewController one, but we can create an extension for any type of Class, like Array, String, Int, etc.

Here’s an example of type Array:

extension Array {
    mutating func shuffle() {
        for _ in 0..<10 /*self.count*/ {
            sortInPlace { (_,_) in arc4random() < arc4random() }
        }
    }
}

You’ll call the shuffle() function inside the Class as it follows:

myArray.shuffle()

You can instantiate multiple functions inside an extension, check out this code:

extension UIViewController {
    func printSomething(_ message:String) {
        print(message)
}
    
func scaleImageToMaxWidth(image: UIImage, newWidth: CGFloat) -> UIImage {
    let scale = newWidth / image.size.width
    let newHeight = image.size.height * scale
    UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
    image.draw(in: CGRect(x:0, y:0, width:newWidth, height:newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
    }
}

We can use the scaleImageToMaxWidth() in this way:

myImageView.image = scaleImageToMaxWidth(image: myUIImage, newWidth: 600)

You can also use extensions to conform to a protocol. Here’s how:

class DetailViewController: UIViewController {
    // code here...
}

extension DetailViewController: CLLocationManagerDelegate {
    // location code here...
}

As shown above, you can break up and group a class’ code by placing the functionality of each protocol into its own extension. The extension lets the base class adopt a protocol, so you can add the protocol-specific code to the extension.

Conclusion

That’s all for this article. Hope you enjoyed it, feel free to post comments or any feedback.

Buy me a coffee - XScoder - thanks for your support
Your support will be highly appreciated 😉