字符串索引 Swift 3

String Indices Swift 3

我是 Swift 3 的初学者,遇到了一个使用字符串索引检索字符的示例。我没有安装 swift 3 但我怀疑与解释不同的一件事。不知道,是bug,写错还是什么的。以下是 "The Swift Programming Language(Swift 3 beta)".

第 166 页的示例
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.

有人可以解释这种行为吗?

来自 "String Indices" 部分的 documentation

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.

这意味着 endIndex 实际上很像字符串的长度,最后一个字符位于索引 endIndex - 1

所以输出是正确的。此外,该文档页面上给出了相同的 "Guten Tag!" 示例。