为什么Swift中的startIndex不等于endIndex移到String中的startIndex位置? [英] Why is startIndex not equal to endIndex shifted to startIndex position in String in Swift?
问题描述
查看程序:
let s = "1"
print(s.startIndex)
print(s.index(before: s.endIndex))
print(s.index(before: s.endIndex) == s.startIndex)
它返回:
Index(_rawBits: 0)
Index(_rawBits: 256)
true
因此,用rawBits 0和256表示字符串中的相同位置.为什么?
索引的原始位是实现细节.如您在示例中所见,两个值相等(对于==
,它们返回true).
对于当前的实现方式,设置了位8,该位不属于该位置. 这是缓存到的偏移量值告诉您下一个字素有一个字节(直到您计算endIndex才知道).
Look at the program:
let s = "1"
print(s.startIndex)
print(s.index(before: s.endIndex))
print(s.index(before: s.endIndex) == s.startIndex)
It returns:
Index(_rawBits: 0)
Index(_rawBits: 256)
true
So, the same position in the string is represented with rawBits 0 and 256. Why?
The raw bits of the index are an implementation detail. As you see in your example, the two values are equal (they return true for ==
).
As to the current implementation, bit 8 is set, which is not part of the position. That's a cached value for the offset to the next grapheme cluster, which is 1 byte away. It's telling you that there's one byte to the next grapheme (which it didn't know until you calculated the endIndex).
这篇关于为什么Swift中的startIndex不等于endIndex移到String中的startIndex位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!