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

193
Views
Comportamiento diferente del índice (después de :) en Collection y String

Tengo curiosidad, por qué este código funciona sin ningún tipo de error:

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

Pero si intentamos repetir este código con el tipo String , obtenemos un error:

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

De acuerdo con los documentos deCollection y String , todos tienen la misma declaración:

Un índice válido de la colección. debo ser menor i endIndex .

¿Es un error o todo funciona como debería? Estoy usando Swift 4.2.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Si vamos al código fuente de Array , podemos encontrar:

 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 }

En este caso, podemos reescribir código como este y finalmente obtener el bloqueo:

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

Por lo tanto, todo funciona "como se esperaba" para el tipo de Array , pero debemos verificar el index de resultados por sí mismo, si no queremos que se bloquee en el tiempo de ejecución.

PS Enlace útil de @ MartinR : https://forums.swift.org/t/behaviour-of-collection-index-limitedby/19083/3

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!