问题
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:
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]
来源:https://stackoverflow.com/questions/28674399/swift-error-cannot-assign-to-immutable-value