获取数组排序的索引

Getting indices of array sort

将一些较旧的 AS3 代码移植到 Swift 我在代码中遇到了一个障碍...在 AS3 中,您可以进行数组排序操作 return 排序结果索引的数值数组, 例如

var indices = columns[0].sort(Array.RETURNINDEXEDARRAY | Array.CASEINSENSITIVE);

If you specify a value of 8 or Array.RETURNINDEXEDARRAY for the sortOptions argument of the ...args parameter, Flash returns a sorted numeric array of the indices that reflects the results of the sort and does not modify the array. (AS3 API)

Swift 4 中有任何解决方案可以给我排序的索引吗?

您可以枚举数组,按元素排序并映射元素偏移量:

let array = [1,3,2,5,4]
let sortedIndices = array.enumerated()
                  .sorted{ [=10=].element < .element }
                  .map{ [=10=].offset }
sortedIndices   // [0, 2, 1, 4, 3]

如果您愿意,您还可以扩展 Collection 并实现您自己的方法,前提是您将其元素限制为 Comparable 协议:

extension Collection where Element: Comparable {
    func sortedIndices() -> [Int] {
        return enumerated()
            .sorted{ [=11=].element < .element }
            .map{ [=11=].offset }
    }
}

let array = [1,3,2,5,4]
let sortedIndices = array.sortedIndices()
sortedIndices   // [0, 2, 1, 4, 3]

另一种选择是添加一个闭包作为参数以允许按以下方式排序:

extension Collection where Element: Comparable {
    func sortedIndices() -> [Int] {
        return sortedIndices(by: <)
    }
}
extension Collection {
    func sortedIndices(by condition: (Element, Element) -> Bool) -> [Int] {
        return enumerated()
            .sorted{ condition([=13=].element,.element) }
            .map{ [=13=].offset }
    }
}

let array = [1,3,2,5,4]
let sortedIndices = array.sortedIndices(by: >)
sortedIndices    // [3, 4, 1, 2, 0]