[swift-users] Simplify chained calls

Adriano Ferreira adriano.ferreira at me.com
Tue Jun 28 09:50:13 CDT 2016


Hi everyone!

I’m experimenting with this functional selection sort code and I wonder if anyone could help me simplify the portion indicated below.


// Swift 3

func selectionSort(_ array: [Int]) -> [Int] {

    guard array.count > 1, let minElement = array.min() else {
        return array
    }

    let indexOfMinElement = array.index(of: minElement)!

    // All of this just to filter out the first smallest element and return the rest
    // Also tried ‘suffix(from:)' here, but couldn’t make it work properly
    let rest = array.enumerated()
                    .filter({ index, _ in index != indexOfMinElement })
                    .map({ _, element in element })

    return [minElement] + selectionSort(rest)
}


By the way, it feels really weird to chain method calls like this in Swift 3, particularly due to the mixing of terms of art (e.g. “filter” and “map”) with other methods that follow the -ed/-ing rules from the API guidelines (e.g. enumerated).

Best,

— A
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160628/a61de4b5/attachment.html>


More information about the swift-users mailing list