Swift error: Cannot assign to immutable value

Swift error: Cannot assign to immutable value

我收到此代码段的上述错误:

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

    for object in array {

        if object is [AnyObject] {

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

有什么想法吗?

for 提取的项目 object 是不可变的。您应该迭代数组的 indices

并且,该项目是 AnyObject 您不能在不转换的情况下将其传递给 inout array: [AnyObject] 参数。在这种情况下,您应该将其转换为可变 [AnyObject] 然后 重新分配 它:

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]