VYT VYT - 5 months ago 12
Swift Question

How to sort the array of Range<Index> in swift?

I have an array of Range Indexes resulting from searching for all positions of several short strings in one long string. I need an array of these sorted Ranges from smaller index to bigger one. How can I do Ranges sorting ?

Answer

Swift 2 (original answer)

You could use the .startIndex property of each range for sorting the ranges.

Example:

let words = "Hello world"

let range1 = words.rangeOfString("world")!
let range2 = words.rangeOfString("Hello")!
let range3 = words.rangeOfString("o w")!

let ranges = [range1, range2, range3]  // ["6..<11", "0..<5", "4..<7"]

let sortedRanges = ranges.sort { $0.startIndex < $1.startIndex }

sortedRanges  // ["0..<5", "4..<7", "6..<11"]

Swift 3

The same, but use .lowerBound instead of .startIndex:

if let range1 = words.range(of: "world"),
        range2 = words.range(of: "Hello"),
        range3 = words.range(of: "o w") {
    let ranges = [range1, range2, range3]
    let sortedRanges = ranges.sorted { $0.lowerBound < $1.lowerBound }
    sortedRanges // [{lowerBound 0, upperBound 5}, {lowerBound 4, upperBound 7}, {lowerBound 6, upperBound 11}]
}

Also note that sort is now sorted.

Comments