The implementation below only works as a method sortedin the standard library without further restriction.
extension RandomAccessCollection {
public func stableSorted(by areInIncreasingOrder: (Iterator.Element, Iterator.Element) -> Bool?) -> [Iterator.Element] {
let sorted = self.enumerated().sorted { (one, another) -> Bool in
if let result = areInIncreasingOrder(one.element, another.element) {
return result
} else {
return one.offset < another.offset
}
}
return sorted.map{ $0.element }
}
}
. , , , , .