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
iendIndex.
¿Es un error o todo funciona como debería? Estoy usando Swift 4.2.
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