(Swift) 在函数内部的 for-in 循环的返回值和循环后的返回值之间感到困惑。

huangapple go评论66阅读模式
英文:

(Swift) Confused between a return value of a for-in loop within a function, and a return value that comes after the loop (within the function))

问题

I am confused with the following code.

func allTestsPassed(tests: [Bool]) -> Bool {
    for test in tests {
        if test == false {
            return false
        }
    }
    return true
}

If the code within the if-else statement (within the for-in loop) executes, it returns false.

But the code following the for-in loop is: return true.

Two different boolean values returned within a function.

When I execute print(allTestsPassed([false])) it prints 'false'.

It seems to disregard the 'return true' that follows the loop.

I do not understand.

英文:

I am confused with the following code.

func allTestsPassed(tests: [Bool]) -> Bool {
	for test in tests {
		if test == false {
			return false
		}
	}
	return true
}

If the code within the if-else statement (within the for-in loop) executes, it returns false.

But the code following the for-in loop is: return true.

Two different boolean values returned within a function.

When I execute print(allTestsPassed([false])) it prints 'false'.

It seems to disregard the 'return true' that follows the loop.

I do not understand.

答案1

得分: 2

return会停止进程,不会执行其后的任何内容。它只是在那里停止了进程。

要了解更多,请更新逻辑并查看结果。

func allTestsPassed(tests: [Bool]) -> Bool {
    print("逻辑开始")
    var currentNumber: Int = 1
    for test in tests {
        print("currentNumber=\(currentNumber) with value==\(test)")
        if test == false {
            print("因为数据为false而返回")
            return false
        }
        currentNumber += 1
    }
    print("逻辑结束")
    return true
}

案例1:所有输入都为true

现在让我们尝试case 1,其中所有输入都将是true

allTestsPassed(tests: [true, true, true, true])

结果是

逻辑开始
currentNumber=1 with value==true
currentNumber=2 with value==true
currentNumber=3 with value==true
currentNumber=4 with value==true
逻辑结束

案例2:其中一个输入为false

allTestsPassed(tests: [true, true, false, true])

结果是

逻辑开始
currentNumber=1 with value==true
currentNumber=2 with value==true
currentNumber=3 with value==false
因为数据为false而返回

如果您在第二个案例中看到,因为test=false,所以没有看到逻辑结束

希望这些日志能够清楚地解释您的理解...

英文:

return stop the process there and don't execute anything after it. It simply stop the process there.

To understand more let's update logic and see results.

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
}

<hr >

Case 1 : All input is true

Now let's try case 1 where all input will be true

allTestsPassed(tests: [true, true, true, true])

Results is

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

<hr >

Case 2 : One of the input is false

allTestsPassed(tests: [true, true, false, true])

Result is

start of logic
currentNumber=1 with value==true
currentNumber=2 with value==true
currentNumber=3 with value==false
returning number because data is false

<hr>

If you see in second case you don't see end of logic because it do the return when test=false

Hope the logs will clears your understanding...

答案2

得分: 1

return 不仅指定函数应返回的值 - 它还将控制返回给调用者。当执行 allTestsPassed 中的 return 语句时,allTestsPassed 中的其他代码将不会被执行。执行会在你调用 allTestsPassed 的地方继续。

这类似于 breakcontinue,因为它会导致执行“跳转”到其他地方。

请参阅 Swift 语言参考文档

return 语句出现在函数或方法的主体中,导致程序执行返回到调用函数或方法的地方。程序执行会在函数或方法调用后紧随的点继续。

如果你这样调用它:

print(allTestsPassed([false]))

传递 [false] 将导致 if 语句中的 return 执行,因此 allTestsPassed 的其余部分不会被执行。执行将返回给调用者。在这种情况下,print 会使用返回的任何值进行调用。

英文:

return does not just specify what value the function should return - it also returns the control to the caller. When a return statement in allTestsPassed is executed, no other code in allTestsPassed will be executed. Execution continues at wherever you called allTestsPassed.

It is similar to a break or continue, in the sense that it causes execution to "jump" to somewhere else.

See the Swift Language Reference:

> A return statement occurs in the body of a function or method
> definition and causes program execution to return to the calling
> function or method. Program execution continues at the point
> immediately following the function or method call.

If you were calling it like this:

print(allTestsPassed([false]))

Passing [false] would cause the return in the if statement to execute, so the rest of allTestsPassed are not executed. Execution returns to the caller. In this case, print is called with whatever value is returned.

答案3

得分: 0

以下是已翻译的内容:

这个函数有一个循环,它遍历一个接受布尔数组参数并返回布尔值的方法。

循环内的条件检查数组中的每个元素,看它的值是否为false。如果是的话,方法allTestsPassed返回false,因为(我猜)其中一个测试失败了。

如果数组中的所有参数都不为false,那么(再次猜测)所有测试都通过了,这就是为什么循环完成迭代并到达返回true行的原因。

通常情况下,当在代码中放置了一个return语句时,这意味着它下面的任何其他行都不会执行。由于在您的方法中,第一个return语句被包含在条件中,它只会在条件评估为true时执行。

希望这能澄清一些事情。

英文:

Let's explain the function you posted in detail:

func allTestsPassed(tests: [Bool]) -&gt; Bool {
	for test in tests {
		if test == false {
			return false
		}
	}
	return true
}

This function has a for loop that iterates over a method that receives an argument that is an array of booleans and returns a boolean.

The condition within the for loop checks each element in the array and sees if it's value is false. If it is, the method allTestsPassed returns false since (I guess) one of the tests failed.

If none of the arguments in the array evaluate to false, then it means (again, guessing), that all the tests passed and that is why the for loop finishes its iteration and gets to the return true line.

In general, when you put a return statement in code, that means that any other line below it will not execute. Since in your method, the first return statement is surrounded by a condition, it will only execute if the condition evaluates to true.

Hope that clears things up a bit.

huangapple
  • 本文由 发表于 2023年5月21日 14:35:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定