在斯威夫特,我可以使用for-在枚举初始化或重置一个数组? [英] In Swift, can I use a for-in enumeration to initialize or reset an array?

查看:150
本文介绍了在斯威夫特,我可以使用for-在枚举初始化或重置一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有一个雨燕类是布尔类型的数组,声明如下:

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
}

..这给我的错误消息无法分配到'让'值'takenFlag'。

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

出于好奇,我试着用VAR声明它,如:

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.

我99%肯定它是指在这个时候,我不能用foo的数组,通过数组迭代,如果我想改变的每个值,但如果有一种方法可以做到这一点,我会所有的耳朵。

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.

推荐答案

要做到这一点,最好的办法是使用阵列内置的映射功能。

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

cardIsTaken = cardIsTaken.map { isTaken in true }

这篇关于在斯威夫特,我可以使用for-在枚举初始化或重置一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆