8
顯然在Swift 3之前,Range<String.Index>
具有count
屬性。在遷移到Swift 3時,我注意到這個count
屬性現在已經消失了。如何計算Swift 3中2 String.Index
的距離?計算Swift 3中的範圍計數
顯然在Swift 3之前,Range<String.Index>
具有count
屬性。在遷移到Swift 3時,我注意到這個count
屬性現在已經消失了。如何計算Swift 3中2 String.Index
的距離?計算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
是不在夫特3的集合,但它有那些方法 以及並且它們被轉發給串CharacterView
。 您與
let count = string.characters.distance(from: range.lowerBound, to: range.upperBound)
得到同樣的結果一樣敏捷4,字符串集合(再次)。