Swift error: Cannot assign to immutable value

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-14 03:53:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!