[swift-users] Appending '[element]' recursively

Adriano Ferreira adriano.ferreira at me.com
Mon Jun 27 09:48:01 CDT 2016


Hi everyone!

I’m migrating some code from Swift 2.2. to Swift 3 and something weird happened.

Is this is a bug or I’m missing something?

// Swift 2.2

func quickSort(_ array: [Int]) -> [Int] {
    guard array.count > 1 else {
        return array
    }

    let (pivot, rest) = (array.first!, array.dropFirst())

    let lessThan = rest.filter({ $0 < pivot })
    let greaterThanOrEqual = rest.filter({ $0 >= pivot })

    // Can use ‘[pivot]' here, no problem at all
    return quickSort(lessThan) + [pivot] + quickSort(greaterThanOrEqual)
}


// Swift 3

func quickSort(_ array: [Int]) -> [Int] {
    guard array.count > 1 else {
        return array
    }

    let (pivot, rest) = (array.first!, array.dropFirst())

    let lessThan = rest.filter({ $0 < pivot })
    let greaterThanOrEqual = rest.filter({ $0 >= pivot })

    // Cannot use ‘[Int]' here, as in Swift 2.2
    // Error says 'Int' is not convertible to '[Int]'
    let pivotArray = [pivot]
    return quickSort(lessThan) + pivotArray + quickSort(greaterThanOrEqual)
}

Best,

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


More information about the swift-users mailing list