Home > OS >  Swift has error : "thread return -x" to return to the state before expression evaluation&q
Swift has error : "thread return -x" to return to the state before expression evaluation&q

Time:04-04

So i have code in xcode playground and got the error error in code

and this is the excercise i do Return the Factorial Create a function that takes an integer and returns the factorial of that integer. That is, the integer multiplied by all positive lower integers.

and this is my code

func factorial(_ num: Int) -> Int {
var result :Int = 0
for _ in num...1 {
    result = num * (num - 1)
}
return result

}

print(factorial(12)) //error in this line

but in terminal got the output this. error in terminal

CodePudding user response:

The answer is in the error message - the upper bound of the range has to be greater than or equal to the lower.

Therefore you'll need to rewrite the method differently. You also have a fundamental flaw in your code - your maths logic is wrong - result will be overwritten every time, rather than accumulating a total. Adopting a similar approach to the question you can do this:

func factorial(_ num: Int) -> Int {
  var result :Int = 1

  guard num > 0 else {return result}. //0! is 1 not 0
  var num = num
  while num > 0 {
    result *= num
    num -= 1
  }
  return result
}

There is a more elegant way of performing this using recursion, which avoids the ugly var num=num

func fac2(_ num: Int, total: Int = 1) -> Int {
  return num > 0 ? fac2(num-1, total: total * num) : total
}
  • Related