swift - execute both func even the first return true in or statement

Viewed 102

I'm trying to execute both functions but when the first return true, the second function is not executed.

func run() {
    if test1() || test2() {
        doSomething()
    }
}

func test1() -> Bool {
    print("test1")
    return true
}

func test2() -> Bool {
    print("test2")
    return false
}

func DoSomething() {
    print("something")
}

Getting Result ::
test1
something

Wanted Result ::
test1
test2
something

In Android we can use one | do it. But not in swift, if someone knows how to do.

3 Answers

This is because the logical or stops its evaluation if the first operand is true. So, if test1 is true, test2 will not be evaluated at all. It's advisable to store the result of both functions into variables if you want to execute both and perform the or on those stored values.

In swift if functions are called in a lazy way. For your if it's enough of test1() to return true to know the result of the expression so there's no need to call test2(), that's why it's skipped

If you need both methods to be called for some reason, you can try this:

if [test1(), test2()].contains(true) {
    doSomething()
}

This is called short-circuiting, and intentional. In principle it’s merely a performance optimization, but it has a semantic impact (which youre noticing here). In fact, it’s actually required by the specifications of many languages, including C, C++, Java, C++, etc.

The entire premise here is quite fishy. To have noticed that test2 doesn’t run, means that test2 has a side effect (in your example, printing a message). This is a violation of the principle of Command/Query separation. This is bad design, akin to having a ruler that drills the material it measures.

If you provide more detail as to what test1 and test2 actually do, we can probably suggest a better approach.

Related