Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

William Forbes
21,469 Pointsfactorial
Hello, I am trying to right a factorial func, so far I have var n = Int(readLine()!)!
func factorial(input: Int) -> Int { var z = input for i in (0 ..< input).reverse() { z *= i } return(z)
} print(factorial(n))
The issue i am having is that for some reason I cannot pull the z from the equation to use. I tried putting the return in the loop but that ends it immediately? Can anyone assist?
1 Answer

ianhan3
4,263 PointsA recursive function is what you want here. You can run your function inside your function decrementing the number each time by 1. Once the parameter number hits zero, the if statement is true and you simply return 1 instead of multiplying your correct factorial by 0, making it 0.
func factorialize(number: Int) -> Int {
if (number == 0) {
return 1
}
return number * factorialize(number - 1);
}
factorialize(5);
//returns 120