What are extensions and when to use them

suggest change

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.

Extensions in Swift can:

When to use Swift Extensions:

When not to use:

Simple example. Swift 4.2 and later already provide Bool.toggle(), which mutates in place and returns Void. The method below also returns the new value, so the call uses as Bool to pick it over the standard one:

extension Bool {
    public mutating func toggle() -> Bool {
        self = !self
        return self
    }
}

var myBool: Bool = true
print(myBool.toggle() as Bool) // false

Source

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents