swift - for循环条件是否评估了Swift中的每个循环?

标签 swift for-loop

我在工作中有一个小争论:在运行它的项目之前在 swift 中计算数组的大小是一个好习惯吗?什么是更好的代码实践:

选项 A:

    func setAllToFalse() {
        for (var i = 0; i < mKeyboardTypesArray.count; i++ ) {
            self.mKeyboardTypesArray[i] = false
        }
    }

选项B:

    func setAllToFalse() {
        let typesCount = mKeyboardTypesArray.count
        for (var i = 0; i < typesCount; i++ ) {
            self.mKeyboardTypesArray[i] = false
        }
    }

当然,如果我在循环期间不更改数组,则全部。

我确实查看了文档,其中说明了这一点:

The loop is executed as follows:

When the loop is first entered, the initialization expression is evaluated once, to set up any constants or variables that are needed for the loop. The condition expression is evaluated. If it evaluates to false, the loop ends, and code execution continues after the for loop’s closing brace (}). If the expression evaluates to true, code execution continues by executing the statements inside the braces. After all statements are executed, the increment expression is evaluated. It might increase or decrease the value of a counter, or set one of the initialized variables to a new value based on the outcome of the statements. After the increment expression has been evaluated, execution returns to step 2, and the condition expression is evaluated again.

最佳答案

在 Swift 中惯用的表达方式是:

func setAllToFalse() {
    mKeyboardTypesArray = mKeyboardTypesArray.map {_ in false}
}

那样的话,就没有什么可评估的,也没有什么可计算的。

事实上,这会成为一个很好的 Array 方法:

extension Array {
    mutating func setAllTo(newValue:T) {
        self = self.map {_ in newValue}
    }
}

现在你可以说:

mKeyboardTypesArray.setAllTo(false)

或者,您可以这样做(这涉及获取 count,但仅一次):

mKeyboardTypesArray = Array(count:mKeyboardTypesArray.count, repeatedValue:false)

关于swift - for循环条件是否评估了Swift中的每个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235595/

相关文章:

objective-c - swift 错误 : Cannot convert value of type '() throws -> ()' to specified type 'Bool'

python-3.x - for循环消除偶数

ios - 更改 MKAnnotation 引脚颜色

ios - Swift 中的双向链表 : why is only one of the references declared weak?

ios - 如何从 Collection View 中的不可见单元格中删除自定义 View

ios - 应将包标识符添加为 URL 方案以启用 Google 登录

javascript - 将事件监听器添加到使用 javascript 创建的 <li>

c++ - 错误 C3017 : termination test in OpenMP 'for' statement has improper form

javascript for() 循环、split() 和数组问题

python - 使用 for 循环填充字典