[swift-users] Simplify chained calls

Erica Sadun erica at ericasadun.com
Tue Jun 28 21:58:01 CDT 2016


> 
> On Jun 28, 2016, at 8:18 PM, Dan Loewenherz via swift-users <swift-users at swift.org> wrote:
> 
> I’m not sure if you wanted to stick with the pure functional approach, but here’s an alternative that uses Range<Int> to take care of most of the work.
> 
> func selectionSort(_ array: [Int]) -> [Int] {
>     guard let minValue = array.min(), let index = array.index(of: minValue) else {
>         return []
>     }
> 
>     let ranges = [0..<index, index.advanced(by: 1)..<array.endIndex]
>     return [minValue] + selectionSort(ranges.flatMap { array[$0] })
> }
> 

Most everyone is doing two passes, one to get the minimum value, another to get its index.
I aesthetically prefer using enumerate to do both at once.

-- E



More information about the swift-users mailing list