Search code examples
swiftfunctionreturnfor-in-loop

(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.


Solution

  • 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
    }
    

    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
    

    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
    

    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...