Extensions with the Swift standard library
Let's say that, in our application, we needed to calculate the factorial of some integers. A factorial is written as 5!. To calculate a factorial, we take the product of all the positive integers that are less than or equal to the number. The following example shows how we would calculate the factorial of five:
5! = 5*4*3*2*1 5! = 120
We could very easily create a global function to calculate the factorial, and we would do that in most languages, however, in Swift, extensions give us a better way to do this. The Integer type in Swift is implemented as a structure which we can extend to add this functionality directly to the type itself. The following example shows how we can do this:
extension Int {
func factorial() -> Int {
var answer = 1
for x in (1...self).reversed() {
answer *= x
}
return answer
}
} We could now calculate the factorial of any integer, as follows:
print(10.factorial())
If we run this code...