Search code examples
swiftfor-loopvarlet

Swift for var list.enumerated()


I have an array of objects whose type is a struct with mutating functions. So I got this code:

for (index, object) in objects.enumerated() {
     otherArray[index] = object.someMutatingFunction(...)
}

This leads me to this error Cannot use mutating member on immutable value of type 'Blabla' which I can fix by adding var:

for var (index, object) in objects.enumerated() {
     otherArray[index] = object.someMutatingFunction(...)
}

But then I get another warning Variable 'index' was never mutated; consider changing to 'let' constant which I don't know how to fix elegantly. The only idea is too add a new var variable. Is there anything else I can do to prevent this warning?


Solution

  • Prefix the object variable with the var keyword:

    struct S {
        mutating func f() { }
    }
    
    let array = [S(), S()]
    
    for (index, var object) in array.enumerated() {
        object.f()
    }
    

    Note as Hamish points out in the comment to this answer that the elements of the array will not be modified. Only the local copy of object inside the scope of the for loop can be modified.

    If you want to modify array you have to declare it var outside the scope of the for loop, then assign to array indices.