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

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

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 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