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