Swift Language Extensions What are Extensions?

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Extensions are used to extend the functionality of existing types in Swift. Extensions can add subscripts, functions, initializers, and computed properties. They can also make types conform to protocols.

Suppose you want to be able to compute the factorial of an Int. You can add a computed property in an extension:

extension Int {
    var factorial: Int {
        return (1..<self+1).reduce(1, combine: *)
    }
}

Then you can access the property just as if it had been included in original Int API.

let val1: Int = 10

val1.factorial  // returns 3628800


Got any Swift Language Question?