您可以枚举您的数组,按其元素对其进行排序并映射元素偏移量:
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]