Swift 中数组的 For-In 循环中迭代器元素的可变性
Mutability of the Iterator Element in a For-In loop with an Array in Swift
我在 Swift 3.0 中有一些代码,用于尝试更新元素数组中的 属性...
for point in listOfPoints {
var pointInFrame : Float = Float(point.position.x * sensorIncomingViewPortSize.width) + Float(point.position.y)
point.status = getUpdateStatus( pointInFrame )
}
但是我得到一个编译错误:
'无法分配给 属性:'point' 是一个 'let' 常量' [for line 3]
有没有办法让 Swift 中的迭代器(点)可变,比如如何使用 'inout' 作为函数参数?
或者您应该以其他方式完成此任务?
提前致谢。
斯坦
只需将其更改为 var
而不是声明 point
的 let
。 let
是 constant
.
完成此操作的另一种方法:
for i in 0 ... myStructArray.count - 1 {
var st = myStructArray[i]
st.someStringVariable = "xxx" // do whatever you need with the struct
st.someIntVariable = 123 // do more stuff
// last step (important!):
myStructArray[i] = st // necessary because structs are VALUE types, not reference types.
}
如果只需要改变一处,可以省略将局部变量(示例中的st
)定义为数组元素,然后再将数组元素设置为等于局部变量的步骤多变的。但是,如果您要对元素进行大量更改,创建局部变量可能更简洁,对它进行所有更改,然后将该变量分配回数组元素。
如果数组是 Class 而不是 Struct,则不需要最后一步返回赋值(引用类型 -- Class,与值类型 -- Struct) .
我在 Swift 3.0 中有一些代码,用于尝试更新元素数组中的 属性...
for point in listOfPoints {
var pointInFrame : Float = Float(point.position.x * sensorIncomingViewPortSize.width) + Float(point.position.y)
point.status = getUpdateStatus( pointInFrame )
}
但是我得到一个编译错误: '无法分配给 属性:'point' 是一个 'let' 常量' [for line 3]
有没有办法让 Swift 中的迭代器(点)可变,比如如何使用 'inout' 作为函数参数?
或者您应该以其他方式完成此任务?
提前致谢。
斯坦
只需将其更改为 var
而不是声明 point
的 let
。 let
是 constant
.
完成此操作的另一种方法:
for i in 0 ... myStructArray.count - 1 {
var st = myStructArray[i]
st.someStringVariable = "xxx" // do whatever you need with the struct
st.someIntVariable = 123 // do more stuff
// last step (important!):
myStructArray[i] = st // necessary because structs are VALUE types, not reference types.
}
如果只需要改变一处,可以省略将局部变量(示例中的st
)定义为数组元素,然后再将数组元素设置为等于局部变量的步骤多变的。但是,如果您要对元素进行大量更改,创建局部变量可能更简洁,对它进行所有更改,然后将该变量分配回数组元素。
如果数组是 Class 而不是 Struct,则不需要最后一步返回赋值(引用类型 -- Class,与值类型 -- Struct) .