【问题标题】:Getting indices of array sort获取数组排序的索引
【发布时间】:2018-03-07 04:14:45
【问题描述】:

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

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

如果您将值 8 或 Array.RETURNINDEXEDARRAY 指定为 ...args 参数的 sortOptions 参数,Flash 返回一个排序的 反映排序结果的索引的数值数组和 不修改数组。 (AS3 API)

在 Swift 4 中有什么可用的解决方案可以给我排序的索引吗?

【问题讨论】:

    标签: arrays swift sorting actionscript-3


    【解决方案1】:

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

    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 协议:

    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]
    

    【讨论】:

    • 采用排序闭包的sortedIndicesBy 怎么样?
    • @vacawama 这是一个不错的选择,我也在考虑不区分大小写的排序
    • 太棒了!感谢@LeoDabus 的回答
    • extension Collection where Element: Comparable { func sortedIndices() -&gt; [Int] { return sortedIndices(by: &lt;) } }
    • 您可以通过仅将 Collection 扩展为闭包版本并将 Collection 与 Comparable 扩展为默认情况。
    猜你喜欢
    • 2011-06-19
    • 2013-07-24
    • 2014-11-06
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    相关资源
    最近更新 更多