3

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?

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks a lot. I do not understand it completely, but it works ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.