Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate range count in Swift 3

Tags:

swift

swift3

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.Indexes in Swift 3?

like image 318
Era Avatar asked Sep 15 '16 08:09

Era


1 Answers

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).

like image 162
Martin R Avatar answered Oct 15 '22 20:10

Martin R