0

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?

2
  • 4
    In Xcode, if you option-click on endindex it says A string’s “past the end” position—that is, the position one greater than the last valid subscript argument. Commented Nov 12, 2017 at 19:59
  • Perfectly understood... thanks Commented Nov 12, 2017 at 22:01

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.