1

I am beginner of Swift 3 and came across one example to retrieve a character using string indices. I do not have swift 3 installed but I doubt one thing that is different from explanation. I do not know, it is bug, writing mistake or what. Below is a example from page 166 of "The Swift Programming Language(Swift 3 beta)".

let greeting = "Guten Tag!"

greeting[greeting.startIndex] //Prints G according to text. Fine according to definition.

greeting[greeting.index(before:greeting.endIndex)] //Prints ! according to text. Now if you look at greeting String, the character before endIndex is g. It must print g according to definition.

greeting[greeting.index(after:greeting.startIndex)] //Prints u according to text and is right according to definition also.

Somebody can explain this behaviour?

1 Answer 1

1

From the documentation in section "String Indices":

The endIndex property is the position after the last character in a String. As a result, the endIndex property isn’t a valid argument to a string’s subscript.

This means that endIndex is actually quite like the length of the string and the last character is at index endIndex - 1.

So the output is correct. Also, the same "Guten Tag!" example is given on that documentation page.

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

1 Comment

I will, after 7 minutes. :)

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.