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

Milos Rankovic milos at milos-and-slavica.net
Mon Apr 11 13:28:48 CDT 2016


Hi Taras,

> On 11 Apr 2016, at 08:48, Taras Zakharko via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 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]) })
>     }
> }

Just a side note that you could also:

extension SequenceType {
	func order(@noescape isOrderedBefore: (Generator.Element, Generator.Element) -> Bool) -> [Int] {
		return enumerate().sort{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
	}
}

(0...3).reverse().order(<) // [3, 2, 1, 0]

This way you can `order` all sequences, and it is more efficient as you don’t fetch elements by index inside the `isOrderedBefore`. (You could also *not* `map` at the end and return all the elements along with their original indexes.)

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


More information about the swift-evolution mailing list