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

195
Visualizações
Different behavior of index(after:) in Collection and String

I'm curious, why this code works without any kind of error:

let a = [1]
print(a.index(after: a.endIndex)) // 2

But if we try to repeat this code with String type, we get an error:

let s = "a"
print(s.index(after: s.endIndex)) // Fatal error: Can't advance past endIndex

According to Collection and String docs, they all have same statement:

A valid index of the collection. i must be less than endIndex.

Is it a bug or all works as it should? I'm using swift 4.2.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If we go to the source code of Array, we can find:

public func index(after i: Int) -> Int {
    // NOTE: this is a manual specialization of index movement for a Strideable
    // index that is required for Array performance.  The optimizer is not
    // capable of creating partial specializations yet.
    // NOTE: Range checks are not performed here, because it is done later by
    // the subscript function.
    return i + 1
}

In this case, we can rewrite code like this and finally get the crash:

let a = [1]
let index = a.index(after: a.endIndex)
print(a[index])

So, all works "as expected" for Array type, but we must check the result index by yourself, if we don't want to get crash at runtime

P.S. Useful link by @MartinR: https://forums.swift.org/t/behaviour-of-collection-index-limitedby/19083/3

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