Reputation: 73
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
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