Swift中的每个循环都会评估for循环条件吗? [英] Is the for loop condition evaluated each loop in Swift?

查看:74
本文介绍了Swift中的每个循环都会评估for循环条件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在讨论一个小问题:在遍历所有项目之前迅速计算Array的大小是一种好习惯吗?什么是更好的代码实践:

I have a small debate at work: Is it a good practice to calculate the size of the Array in swift before running over it's items? What would be a better code practice:

选项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
        }
    }

所有,当然,如果我在循环期间不更改Array.

All, of course, if I don't alter the Array during the loops.

我确实查阅了说明以下内容的文档:

I did go over the documentation, which states this:

循环执行如下:

The loop is executed as follows:

首次进入循环时,初始化表达式为 评估一次,以设置所需的任何常量或变量 为循环.条件表达式被评估.如果它评估 为假,循环结束,并且在for之后继续执行代码 循环的右大括号(}).如果表达式的计算结果为true,请编写代码 通过在花括号内执行语句,继续执行. 执行完所有语句后,增量表达式为 评估.它可能会增加或减少计数器的值,或者 根据 陈述的结果.在增量表达式被 评估,执行返回到步骤2,然后条件表达式 再次评估.

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中这种惯用的说法是:

The idiomatic way to say this in Swift is:

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

那样,就没有什么可评估的,也没有可数的.

That way, there is nothing to evaluate and nothing to count.

实际上,这将是一个不错的Array方法:

In fact, this would make a nice Array method:

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

现在您可以说:

mKeyboardTypesArray.setAllTo(false)

或者,您可以通过这种方式进行操作(这涉及到count,但只能执行一次):

Alternatively, you could do it this way (this involves taking the count, but only once):

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

这篇关于Swift中的每个循环都会评估for循环条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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