2016-09-15 73 views
8

顯然在Swift 3之前,Range<String.Index>具有count屬性。在遷移到Swift 3時,我注意到這個count屬性現在已經消失了。如何計算Swift 3中2 String.Index的距離?計算Swift 3中的範圍計數

回答

12

從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在夫特3的集合,但它有那些方法 以及並且它們被轉發給串CharacterView。 您與

let count = string.characters.distance(from: range.lowerBound, to: range.upperBound) 

得到同樣的結果一樣敏捷4,字符串集合(再次)。