我在工作中有一个小争论:在运行它的项目之前在 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/