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.
3
Answers
Let’s explain the function you posted in detail:
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.
return
does not just specify what value the function should return – it also returns the control to the caller. When areturn
statement inallTestsPassed
is executed, no other code inallTestsPassed
will be executed. Execution continues at wherever you calledallTestsPassed
.It is similar to a
break
orcontinue
, in the sense that it causes execution to "jump" to somewhere else.See the Swift Language Reference:
If you were calling it like this:
Passing
[false]
would cause thereturn
in the if statement to execute, so the rest ofallTestsPassed
are not executed. Execution returns to the caller. In this case,print
is called with whatever value is returned.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.
Case 1 : All input is true
Now let’s try
case 1
where all input will betrue
Results is
Case 2 : One of the input is false
Result is
If you see in second case you don’t see
end of logic
because it do the return when test=falseHope the logs will clear your understand…