arrays - 获取数组排序的索引

标签 arrays swift sorting actionscript-3

将一些较旧的 AS3 代码移植到 Swift 我在代码中遇到了一个障碍......在 AS3 中,你可以让数组排序操作返回排序结果索引的数字数组,例如

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{ $0.element < $1.element }
                  .map{ $0.offset }
sortedIndices   // [0, 2, 1, 4, 3]

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

extension Collection where Element: Comparable {
    func sortedIndices() -> [Int] {
        return enumerated()
            .sorted{ $0.element < $1.element }
            .map{ $0.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($0.element,$1.element) }
            .map{ $0.offset }
    }
}

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

关于arrays - 获取数组排序的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49144009/

相关文章:

c# - 带条件排序的 LINQ OrderBy/ThenBy

javascript - 显示过滤数组的长度

java - 将 java.util.Collections 转换为整数数组

arrays - Perl "scalar"函数在空数组上返回 "1"

快速浏览字典

php - 使用 "sort"列排列 MySQL 表中的行

django-admin - 按 __unicode()__ 方法的输出对 Django 管理更改列表列进行排序

c - 如何在 C 中将整数转换为数字数组?

ios - startMonitoring 不适用于 "WhenInUseAuthorization"权限

swift - iOS 14、Swift UI 2 更改 NavigationLink 内所选列表项的背景颜色