计算Swift 3中的范围计数

Eri*_*ner 10 swift swift3

显然在Swift 3之前,Range<String.Index>有一个count属性.在迁移到Swift 3时,我注意到这个count属性现在已经消失了.如何计算String.IndexSwift 3中2 es 之间的距离?

Mar*_*n R 18

从Swift 3开始,所有指数计算均由集合本身完成,比较SE-0065 - 收集的新模型和 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
}
Run Code Online (Sandbox Code Playgroud)

实际上,String不是 Swift 3中的集合,但它也有这些方法,它们被转发到字符串CharacterView.你得到相同的结果

    let count = string.characters.distance(from: range.lowerBound, to: range.upperBound)
Run Code Online (Sandbox Code Playgroud)

从Swift 4开始,字符串就是集合(再次).