find the factorial of a number in swift

main.swift
func factorial(_ n: Int) -> Int {
    if n == 0 {
        return 1
    } else {
        return n * factorial(n - 1)
    }
}

let number = 5
let fact = factorial(number)
print("Factorial of \(number) is \(fact)")
212 chars
12 lines

In this code, we define a function named factorial that takes an integer parameter n and returns the factorial of n.

The function uses recursion to calculate the factorial. If the number is zero, the function returns 1. Otherwise, it multiplies the number with the factorial of (n-1) and returns the result.

We then call the factorial function on a number (5 here) and print the result. The output for this code would be:

main.swift
Factorial of 5 is 120
22 chars
2 lines

gistlibby LogSnag