显然在 Swift 3 之前,一个 Range<String.Index>
有一个count
属性(property)。在迁移到 Swift 3 时,我注意到这个 count
属性(property)现在没有了。如何计算 2 String.Index
之间的距离es 在 Swift 3 中?
最佳答案
从 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 开始,字符串(再次)是集合。
关于swift - 在 Swift 3 中计算范围计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39505923/