【问题标题】:Why is startIndex not equal to endIndex shifted to startIndex position in String in Swift?为什么 startIndex 不等于 endIndex 在 Swift 中转移到 String 中的 startIndex 位置?
【发布时间】:2019-05-09 19:07:45
【问题描述】:

看程序:

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 表示。为什么?

【问题讨论】:

  • 你为什么要看rawBits
  • 可能是 print() 命令的问题,而不是相等性

标签: swift string indexing


【解决方案1】:

索引的原始位是一个实现细节。正如您在示例中看到的,这两个值是相等的(对于==,它们返回 true)。

对于当前的实现,设置了第 8 位,这不是位置的一部分。 That's a cached value for the offset to the next grapheme cluster, which is 1 byte away. 它告诉你下一个字素有一个字节(直到你计算出 endIndex 才知道)。

【讨论】:

    【解决方案2】:

    两个String.Indexes之间的Equality定义在_rawBits的高50位,也就是orderingValue,如下:

    扩展 String.Index: Equatable {
      @inlinable @inline(__always)
      公共静态函数 == (lhs: String.Index, rhs: String.Index) -> Bool {
        返回 lhs.orderingValue == rhs.orderingValue
      }
    }

    由于0 &>> 14256 &>> 14 都等于0,所以位置是相等的,因此索引被认为是相等的。


    &>> 是右移位的中缀运算符,将移位量屏蔽为 64 位。

    【讨论】:

      猜你喜欢
      • 2013-05-19
      • 2012-05-07
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 2014-11-26
      相关资源
      最近更新 更多