Error with String endIndex in Swift

I have the following code:

let hello = "Hola"
let indexI = hello.startIndex
let indexF = hello.endIndex
hello[indexI] // "H"
hello[hello.startIndex] // H
hello[hello.index(after: indexI)] // o

hello[indexF] // Fatal error: Can't form a Character from an empty String

But I have an error in hello[indexF]Why?

1 answer

  • answered 2017-11-12 20:00 Moe Abdul-Hameed

    If you want to access the last element you need to replace:

    let indexF = hello.endIndex
    

    With:

    let indexF = hello.index(before: hello.endIndex)
    

    The documentation of endIndex says:

    A string’s “past the end” position—that is, the position one greater than the last valid subscript argument.