Home > Software design >  Execution of combined Booleans in swift
Execution of combined Booleans in swift

Time:05-14

I'm having a question about a computed property where I'm using a combination of computed Booleans to get a result. I understand the logic behind the code, but I'm using some print statements in my code (for debugging) which are not getting called when one of the earlier Booleans is false. If check1 is false, there is no need to execute check2 and check3 because the outcome will be false, but I still want to access the print statements in that code. In the example here I just check if the var is being accessed, in my app it's more complicated which is why I would love to get the result of some logic printed out. Any idea how to solve this ? So basically I would love to view the result of all calls in the debugger, no matter if the outcome is true or false.

var checkedIsTrue: Bool {
    
    var check1: Bool {
        print("checked 1")
        return 2 < 1 ? true : false // When false, check2 and check3 are not executed
    }
    
    var check2: Bool {
        print("checked 2")
        return 3 < 4 ? true : false
    }
    
    var check3: Bool {
        print("checked 3")
        return 4 < 5 ? true : false
    }
    
    if check1 && check2 && check3 {
        return true
    } else {
        return false
    }
}

print(checkedIsTrue ? "check is OK" : "check is NOK")

CodePudding user response:

&& is a “short-circuiting” operator: If the left operand is false then the right operand is not evaluated at all.

Here are two possible options if you want (for debugging purposes) all boolean expressions to be evaluated.

Option 1: Create an array with all boolean results before combining them:

if [check1, check2, check3].allSatisfy({ $0 }) { ... }

Option 2: Define your own “logical AND” operator which does not short-circuit:

infix operator &&&: LogicalConjunctionPrecedence

extension Bool {
    static func &&&(left: Bool, right: Bool) -> Bool {
        left && right
    }
}

if check1 &&& check2 &&& check3 { ... }

There are probably more ways to achieve this.

  • Related