字符串索引 swift 3.



我是 Swift 3 的初学者,遇到了一个使用字符串索引检索字符的示例。我没有安装 swift 3,但我怀疑一件事与解释不同。我不知道,这是错误,写作错误还是什么。下面是"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.

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

来自"字符串索引"部分中的文档:

属性是字符串中最后一个字符之后的位置。因此,endIndex 属性不是字符串下标的有效参数。

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

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

最新更新