显然在Swift 3之前,Range<String.Index>
有一个count
属性。在迁移到Swift 3时,我注意到这个count
属性现在已经消失了。如何计算Swift 3中2 String.Index
es之间的距离?
答案 0 :(得分:17)
从Swift 3开始,所有索引计算都由集合本身完成, 比较SE-0065 – A New Model for Collections and Indices对Swift进化的影响。
示例:
let string = "abc 1234 def"
if let range = string.range(of: "\\d+", options: .regularExpression) {
let count = string.distance(from: range.lowerBound, to: range.upperBound)
print(count) // 4
}
实际上,String
不是 Swift 3中的一个集合,但它有这些方法
同样,它们被转发到字符串CharacterView
。
您可以使用
let count = string.characters.distance(from: range.lowerBound, to: range.upperBound)
从Swift 4开始,字符串就是集合(再次)。