Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 632
user2156649 Avatar asked Jun 12 '26 11:06

user2156649


1 Answers

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]
like image 194
rintaro Avatar answered Jun 15 '26 05:06

rintaro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!