user2156649
user2156649

Reputation: 73

Swift error: Cannot assign to immutable value

I got the error above for this code snippet:

func store(name: String, inout array: [AnyObject]) {

    for object in array {

        if object is [AnyObject] {

            store(name, &object)
            return
        }
    }
    array.append(name)
}

Any ideas?

Upvotes: 3

Views: 8426

Answers (1)

rintaro
rintaro

Reputation: 51911

the item object extracted with for is immutable. You should iterate indices of the array instead.

And, the item is AnyObject you cannot pass it to inout array: [AnyObject] parameter without casting. In this case, you should cast it to mutable [AnyObject] and then reassign it:

func store(name: String, inout array: [AnyObject]) {
    for i in indices(array) {
        if var subarray = array[i] as? [AnyObject] {
            store(name, &subarray)
            array[i] = subarray // This converts `subarray:[AnyObject]` to `NSArray`
            return
        }
    }
    array.append(name)
}

var a:[AnyObject] = [1,2,3,4,[1,2,3],4,5]
store("foo", &a) // -> [1, 2, 3, 4, [1, 2, 3, "foo"], 4, 5]

Upvotes: 1

Related Questions