Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda