Reputation:
Apparently before Swift 3, a Range<String.Index>
had a count
property. While migrating to Swift 3 I noticed that this count
property is now gone. How do I calculate the distance between 2 String.Index
es in Swift 3?
Upvotes: 10
Views: 6744
Reputation: 539795
As of Swift 3, all index calculations are done by the collection itself, compare SE-0065 – A New Model for Collections and Indices on Swift evolution.
Example:
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
}
Actually, String
is not a collection in Swift 3, but it has those methods
as well and they are forwarded to the strings CharacterView
.
You get the same result with
let count = string.characters.distance(from: range.lowerBound, to: range.upperBound)
As of Swift 4, strings are collections (again).
Upvotes: 23