本文介绍了快速错误:无法分配给不变值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于此代码段,我收到了上面的错误:

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)
}

有什么想法吗?

推荐答案

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

the item object extracted with for is immutable. You should iterate indices of the array instead.

而且,该项是AnyObject,如果不进行强制转换,则不能将其传递给inout array: [AnyObject]参数.在这种情况下,应将其强制转换为可变的[AnyObject],然后重新分配:

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]

这篇关于快速错误:无法分配给不变值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 21:15