我对以下代码感到困惑。
func allTestsPassed(tests: [Bool]) -> Bool {
for test in tests {
if test == false {
return false
}
}
return true
}
如果 if-else 语句内(for-in 循环内)的代码执行,则返回 false。
但是 for-in 循环后面的代码是:return true
。
函数内返回两个不同的 bool 值。
当我执行 print(allTestsPassed([false]))
时,它会打印“false”。
它似乎忽略了循环后面的“return true”。
我不明白。
最佳答案
return 停止该进程并且之后不执行任何操作。它只是停止那里的过程。
为了了解更多信息,让我们更新逻辑并查看结果。
func allTestsPassed(tests: [Bool]) -> Bool {
print("start of logic")
var currentNumber : Int = 1
for test in tests {
print("currentNumber=\(currentNumber) with value==\(test)")
if test == false {
print("returning number because data is false")
return false
}
currentNumber += 1
}
print("end of logic")
return true
}
情况 1:所有输入均为 true
现在让我们尝试情况 1
,其中所有输入均为 true
allTestsPassed(tests: [true, true, true, true])
结果是
start of logic
currentNumber=1 with value==true
currentNumber=2 with value==true
currentNumber=3 with value==true
currentNumber=4 with value==true
end of logic
情况 2:其中一个输入为 false
allTestsPassed(tests: [true, true, false, true])
结果是
start of logic
currentNumber=1 with value==true
currentNumber=2 with value==true
currentNumber=3 with value==false
returning number because data is false
如果您在第二种情况下看到,您不会看到逻辑结束
,因为它在test=false
时返回
希望日志能够澄清您的理解...
关于swift - (Swift) 混淆了函数内 for-in 循环的返回值和循环之后的返回值(函数内)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76298597/