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.
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: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.