Order of evaluation in guard / if statement

Hi,

I would like to know if the order of the evaluation of the conditions in guard and if statements are evaluated in the same order as specified in code ?

Reason for asking

  • I have a simple condition followed by a complex (expensive) condition, just wanted to ensure that the complex condition is evaluated only after the simple condition is satisfied.

Question:

  • Is the order of evaluation guaranteed both in guard and if statements ?
  • Or there could be compiler optimisations or other factors that might cause it to be evaluated in a different order ?

Code:

func simpleCondition() -> Bool {
    return false
}

func complexCondition() -> Bool {
    return true //Assume this is an expensive operation
}

func f1() {
    
    guard simpleCondition(),
        complexCondition() else {
        return
    }
}
1 Like

The order must be respected and can be very helpful when it's meaningful. Your example is among the reasons. For a conjunction, it is sufficient for the lhs to fail to evaluate the whole condition. The second condition can depend on the first one in different ways; often these are written in a way that the second condition would crash be the first one false:

if (ptr && ptr->function()) {...}

You can confirm the order by printing it

func simpleCondition() -> Bool {
  print("simpleCondition")
  return false
}
func complexCondition() -> Bool {
  print("complexCondition")
  return true
}
func foo() {
  guard simpleCondition(), complexCondition() else { return }
}
3 Likes

Thanks @anthonylatsis for the clarification