[swift-evolution] [Proposal] Add .order() family of methods to Collection

Taras Zakharko taras.zakharko at uzh.ch
Mon Apr 11 02:48:19 CDT 2016

Swift standard library already offers a useful set of sort() functions. However, it is also often useful to know how the collection should be rearranged in order to become sorted. For example, R defines the order() function which returns a permutation of collection indexes which rearrange the collection in an order. I suggest to add similar functionality to the Swift Collections E.g.:

var out = []
for i in collection.order({$0 < $1}) { out.append(collection[i]) }
// out is now sorted collection

Knowing the sort order is useful in many applications where the data cannot or should not be rearranged and yet some information about the ordering is helpful, e.g. for traversing the collection in a specific way. It is also helpful for maintaining multiple ordering relations associated with the same collection. 

The implementation should be fairly straightforward. E.g. here is an extension method I use:

extension CollectionType {
    func order(@noescape isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) -> Bool) -> [Self.Index] {
        return indices.sort({ isOrderedBefore(self[$0], self[$1]) })



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160411/db7c3ae8/attachment.html>

More information about the swift-evolution mailing list