2
import Foundation


func insertionSort<T where T: Comparable>(var items:[T])-> [T] {

    for (index, _) in items.enumerate().dropFirst() {
        var j = index

        while ((j > 0) && (items[j] < items[j-1])) {
            swap(&items[j], &items[j-1])
            j = j-1
        }
    }
    return items
}


// Test the function
insertionSort([]) // Generic type array is not taking empty array

When I am trying to call insertionSort with empty array, I get

Cannot invoke 'insertionSort' with an argument list of type '([_])'

I am not able to figure out how to fix this.

2
  • @Lu_ var required for items because I am making changes in the array. Commented Jul 22, 2016 at 13:15
  • let tab: [String] = [] let a = insertionSort(tab) swift need declared array type, your sorting is working if it is swift array Commented Jul 22, 2016 at 13:17

1 Answer 1

2

To call generic functions in Swift, Swift needs to be able to infer the generic parameters.

One way giving the type information to Swift, is using an intermediate variable. (Like noted in Lu_'s comment.)

let arr: [Int] = []
let result = insertionSort(arr)

Another way is using as.

let result = insertionSort([] as [Int])

(Remember, var parameter does not modify the actual argument. It just makes a mutable copy, but does not write it back to the original argument. Swift 3 removed var parameters, as it's so confusing. You may need to assign the return value of the function to a variable.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.