In Swift, can I use a for-in enumeration to initialize or reset an array?

落花浮王杯 提交于 2019-12-08 02:04:43

问题


I currently have an array in a Swift class that is of type Bool, declared as follows:

public var cardIsTaken: [Bool]

For purposes of keeping up with a Swift style guide that calls for avoiding indexed for loops when possible, I have something like this:

for takenFlag in cardIsTaken {
    takenFlag = true
}

.. which gives me the error message "cannot assign to 'let' value 'takenFlag'"

Out of curiosity, I tried declaring it with "var", as in:

    for var takenFlag in cardIsTaken {
        takenFlag = true
    }

.. which just gives me a whole slew of different, unrelated error messages.

I am 99% sure it means at this time, I cannot use "for foo in array" to iterate through an array if I want to change each value, but if there IS a way to do it, I'd be all ears.


回答1:


The best way to do this is to use the array's built in mapping function.

cardIsTaken = cardIsTaken.map { isTaken in true }


来源:https://stackoverflow.com/questions/28863292/in-swift-can-i-use-a-for-in-enumeration-to-initialize-or-reset-an-array

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