Index of element in sorted()

2019-02-28 11:09发布

问题:

When you call

sorted(<#source: C#>, <#isOrderedBefore: (C.Generator.Element, C.Generator.Element) -> Bool##(C.Generator.Element, C.Generator.Element) -> Bool#>)

you can access the two source elements for comparison via $0 and $1. But how can I determine the index from where they were taken from the source?

回答1:

You could pass into sorted not a collection of elements, but the indices of the elements:

let a = ["hello","i","must","be","going"]
let idxs = sorted(indices(a)) { a[$0] < a[$1] }
// produces [3, 4, 0, 1, 2]

Or, if you don't like capturing a and wanted the elements themselves passed into the closure, you could pass in a sequence of pairs of the index and the element, like so:

let pairs = sorted(Zip2(indices(a),a)) {
    $0.1 < $1.1
}

Note the result would be an array of (index,element) pairs: [(3, be), (4, going), (0, hello), (1, i), (2, must)]. If you wanted to turn that back into just the elements, you can do map(pairs) { $0.1 }

Also, if you take the just-indices route and want to turn that back into elements later, you can do it with PermutationGenerator:

let values = PermutationGenerator(elements: a, indices: idxs)
println(" ".join(values)) // prints "be going hello i must"


标签: swift sorted