user1107173
user1107173

Reputation: 10764

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

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?

Upvotes: 4

Views: 1640

Answers (1)

rob mayoff
rob mayoff

Reputation: 385690

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)

Upvotes: 7

Related Questions