Search code examples
xcodeswiftswift-playground

Swift - [Int] is not a subtype of @lvalue$T2


I'm trying to do a simple sort function in a swift playground but I get the following error:

Playground execution failed: error: <EXPR>:20:22: error: '[Int]' is not a subtype of '@lvalue $T2'
            swap(&a,k,j) //Here in &a

I have written the following code:

let arr:[Int] = [1,3,53,24,52,1,234,5,3]

func swap(inout a:[Int], num1:Int, num2:Int){
    var value = a[num1]
    a[num1] = a[num2]
    a[num2] = value
}

func sort(a:[Int]){
    var j = 0
    var k = 0
    for (k = j ; k<=a.count; k++){
        if(k != a.count){
            if(a[k] < a[j]){
                swap(&a,k,j)
            }
        }else{
            j++;
        }
    }
 }

print ("\(sort(arr)) is the array")

Any idea of why this does not work? Am I referencing the array incorrectly, thanks!

UPDATE: As Martin R pointed out the errors, here is the corrected code:

var arr:[Int] = [1,3,53,24,52,1,234,5,3]

And the sort function:

func sort(inout a:[Int]) -> [Int]{
var j = 0
var k = 0
for (k = j ; k <= a.count; k++){
    if(k != a.count){
        if(a[k] < a[j]){
            swap(&a,j,k)
        }
    }else{
        j++;
        k = j
    }
}
    return a
}

Finally:

print ("\(sort(&arr)) is the array")

Solution

  • The local parameter a in

    func sort(a:[Int])
    

    is by default a constant. Since you want to modify the passed array, you have to declare that parameter as inout in the same way as in the swap() function:

    func sort(inout a:[Int])
    

    Moreover, the passed array has to be variable:

    var arr:[Int] = [1,3,53,24,52,1,234,5,3]
    

    and you have to prefix it with the ampersand when it is passed as an argument for an in-out parameter, to indicate that it can be modified by the function:

    sort(&arr)
    println(arr)
    

    Note also that

    print ("\(sort(arr)) is the array")
    

    does not print the array result because sort() has no return value.