Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over an array and updating value. error: '@lvalue $T5' is not identical to 'Int'

Tags:

swift

I have the following syntax in Swift:

func basicFunction(anArray:[Int], aValue:Int) -> Int {
    for (var i = 0; i<5; ++i)
    {
        if anArray[i] == 0
        {
            anArray[i] = aValue  //I get an error in XCode
        }
    }
    return 1
}

I get the following Xcode error: '@lvalue $T5' is not identical to 'Int'

enter image description here

What am I doing wrong?

like image 615
user1107173 Avatar asked Mar 19 '23 06:03

user1107173


1 Answers

Function arguments are immutable by default, and the Swift compiler gives terrible error messages.

Anyway, because anArray is immutable, you cannot modify it. That's why you get an error message. Declare it inout:

func basicFunction(inout anArray:[Int], aValue:Int) -> Int {
    for (var i = 0; i<5; ++i) {
        if anArray[i] == 0 {
            anArray[i] = aValue
        }
    }
    return 1
}

Call it with an & in front of the array argument:

basicFunction(&someArray, 99)
like image 87
rob mayoff Avatar answered Mar 22 '23 23:03

rob mayoff