LEARN SWIFT

Buy the PDF

16.1 Defining extensions

Extensions let you extend and add new functionality to an existing type, class, structure or enumeration. You can extend existing types, both your own and those from external libraries or those from Swift itself.

You cannot replace existing functionality, only add new functionality i.e. no monkey-patching allowed.

You declare an extension using the extension keyword, followed by the name of the type that you want to extend.

Lets add some methods to the built-in Integer type.

We can add extensions as either a property or as a method. This example shows how to extend the Swift Int type to add both a property and a function for squaring an integer.

extension Int {
    var squared: Int {
        return(self * self)
    }
    func squaredFunc() -> Int {
        return(self * self)
    }
}

3.squared        // 9
3.squaredFunc()  // 9

In this example we create a class Dog. We can add more functionality to this class later by extending it. For example here we add a description method to the class which wasn’t present when we initially defined it.

class Dog {
    var name = "Timmy"
}

var timmy = Dog()
// timmy.description // error

extension Dog {
    func description() -> String {
        return "A dog named \(self.name)"
    }
}

timmy.description() // “A dog named Timmy”

These examples show how to add computed properties and instance methods as extensions. You can also use extensions to add:

  • convenience initializers (but not deinitializers)
  • type methods
  • subscripts methods

We won’t go into detail on these here as they are similar to how you would implement these when declaring the type, you just use a similar syntax with the extension keyword instead.