Search code examples
swiftsyntaxshort-circuiting

Swift short-circuiting with logical operators not working as expected


var anArray = [3, 2, 1]
func sortAndCheck(array: inout [Int]) -> Bool{
    array.sort()
    return array.contains(3)
}

if anArray.contains(3){
    print(anArray) // Prints [3, 2, 1]
}

if anArray.contains(3) && sortAndCheck(array: &anArray){
    print(anArray) // Prints [1, 2, 3]
}

For the second if statement, since anArray.contains(3) is already true, why does sortAndCheck(array: &anArray) still get evaluated and sort anArray?enter image description here


Solution

  • Short circuiting means that the next part of the expression is not evaluated only if the result is already clear. If the part before && is true then the result can still be both false and true and the next part has to be evaluated.

    The cases are:

    1. true && true => true
    2. true && false => false
    3. false && false => false
    4. false && true => false
    

    And after evaluating the left operand we have:

    true && ??
    

    which can end either in case 1 or 2, which have different results.

    On the other hand, if we had:

    false && ??
    

    Then the result would be either case 3 or 4, which are both false and the expression will short-circuit.