可以枚举数组,按元素对其排序,并映射元素偏移:
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]
如果愿意,还可以扩展集合并实现自己的方法,前提是将其元素约束到可比较的协议:
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]