Mutability of the Iterator Element in a For-In loop with an Array in Swift

只愿长相守 提交于 2019-12-23 13:24:21

问题


I have some code in Swift 3.0 like so for trying to update the property in a array of elements...

for point in listOfPoints {
    var pointInFrame : Float = Float(point.position.x * sensorIncomingViewPortSize.width) + Float(point.position.y)
    point.status = getUpdateStatus( pointInFrame )
}

However I get a compile error of: 'Cannot assign to property: 'point' is a 'let' constant' [for line 3]

Is there anyway to make the iterator (point) mutable in Swift, like how you can use 'inout' for a function parameter?

Or are you supposed to do this task another way?

Thanks in Advance.

Stan


回答1:


Just change it to var instead of let where you declare point. let is a constant.




回答2:


Another way to accomplish this:

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

If you only need to make one change, you can omit the steps of defining the local variable (st in the example) as the array element and then afterwards setting the array element as equal to the local variable. But if you're going to make lots of changes to the element, if may be cleaner to make the local variable, make all the changes to it, and then assign that variable back to the array element.

If the array was of a Class rather than a Struct, that last step of assigning back wouldn't be necessary (reference type -- Class, vs value type -- Struct).



来源:https://stackoverflow.com/questions/40160113/mutability-of-the-iterator-element-in-a-for-in-loop-with-an-array-in-swift

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