What are Extensions
suggest changeExtensions 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, *)
}
}
Then you can access the property as if it had been included in the original Int API. The range used here is only meaningful for a non-negative value. For 0 it returns 1.
let val1: Int = 10
val1.factorial // returns 3628800
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents