Search code examples
iosswiftuiviewbuilder

SwiftUI ViewBuilder: is it guaranteed that in `if/ese` statement `else` clause isn't executed when condition is true?


I ask this because I suddenly realized today that, since the if/else statement we use to build View in SwiftUI is interpreted by ViewBuilder, it may behave differently than the plain old if/else statement in Swift language. Could it be that, for some (e.g. performance) reason, SwiftUI pre-execute both clauses and cache the result? Does anyone know it for sure?

I remember I observed some confusing behavior in the past, which might be explained by this hypothesis. But unfortunately I can't recall an example.


Solution

  • The way a result builder transforms your code is spelled out in SE-0289: Result builders. Section “Selection statements” describes how if/else statements are transformed. It gives the following example:

    Consider the following code:

    if i == 0 {
      "0"
    } else if i == 1 {
      "1"
    } else {  
      generateFibTree(i)
    }
    

    Under this pattern, the example code becomes something like the following:

    let vMerged: PartialResult
    if i == 0 {
      var firstVar = "0"
      var firstBlock = BuilderType.buildBlock(firstVar)
      vMerged = BuilderType.buildEither(first: firstBlock)
    } else if i == 1 {
      var secondVar = "1"
      var secondBlock = BuilderType.buildBlock(secondVar)
      vMerged = BuilderType.buildEither(second:
            BuilderType.buildEither(first: secondBlock))
    } else {
      var elseVar = generateFibTree(i)
      var elseBlock = BuilderType.buildBlock(elseVar)
      vMerged = BuilderType.buildEither(second:
            BuilderType.buildEither(second: elseBlock))
    }
    

    You can also read a detailed description of the transformation algorithm, but I think the example makes it clear enough that it will only execute one branch of an if/else statement.