如何在swift中对Range <index>的数组进行排序?

时间:2015-10-20 12:16:56

标签: arrays swift sorting range

我有一个范围索引数组,这是通过在一个长字符串中搜索几个短字符串的所有位置而得到的。我需要一个从较小索引到较大索引的这些排序范围的数组。我怎样才能进行Ranges排序?

1 个答案:

答案 0 :(得分:3)

Swift 2 (原始回答)

您可以使用每个范围的.startIndex属性对范围进行排序。

示例:

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

相同,但请使用.lowerBound代替.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}]
}

另请注意,sort现在为sorted