Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
Tail Recursion (Tail Call Optimization) in Swift 4

I tried to do the following simple function in Swift:

 func sum (n: Int, currentSum: Int = 0) -> Int {
    return n == 0 ? currentSum :
                    sum(n: n-1,
                        currentSum: currentSum + n)
 }

I expected that the compiler would use tail recursion optimization. But I fall into a (literally :-P) stack overflow problem.

Is there any flag I need to set to make the compiler do such optimization, I made any mistake on my code or this compiler optimization is not available?

Thanks!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

As Martin notes, you won't get TCO in any case unless you turn on the optimizer (-O), but even in that case, there's no way to guarantee that you'll get TCO, and so you really can't rely on it. Swift is not particularly friendly to recursive algorithms. Typically you'd write this as:

func sum(n: Int) -> Int {
    return (1...n).reduce(0, +)    
}

Or to maintain the same computational pattern (i.e. counting down from n to 1):

func sum(n: Int) -> Int {
    return (1...n).reversed().reduce(0, +)
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!