gpt4 book ai didi

inheritance - 协议(protocol)类型对象的 Swift 数组

转载 作者:可可西里 更新时间:2023-11-01 01:06:51 27 4
gpt4 key购买 nike

我有下一个遗产:

protocol P {
var a : Int { get set }
}

class C : P {
var a : Int
...
}

然后我想创建广义数组并通过一些操作遍历它:

class Main {
var array : Array<Proto>
var inst : Proto
...
func foo() {
array.append(C(a:10))
for obj in array {
obj.a = 20 //Error: Cannot assign to the result of this expression
}

inst = C(a:10)
inst.a = 20 //Works correctly

for var i = 0; i < arr.count; ++i {
inst = arr[i]
inst.a = 20 //No problem even here
}
}
}

如果我施放:(obj as C).a = 20 - 那么一切正常。有人可以解释这种行为吗?

最佳答案

问题是for-in循环不允许修改迭代项。来自documentation :

NOTE

The index constant exists only within the scope of the loop. If you want to check the value of index after the loop completes, or if you want to work with its value as a variable rather than a constant, you must declare it yourself before its use in the loop.

您可以尝试以下方法:

    for obj in array {
var c = obj
c.a = 20 // This should work as c is a mutable copy of obj
}

补充:

请注意@ikuramedia 所说的是正确的。上面的代码屏蔽了 obj 是一个值类型的情况,在这种情况下 c 将是它的一个副本并且值 obj 在数组 < strong>不会实际被修改。

关于inheritance - 协议(protocol)类型对象的 Swift 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24404459/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com