Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda