将一些较旧的 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/