How "buildEither" work?

Hello!

I have checked the documentation:

let someNumber = 19
@ArrayBuilder var builderConditional: [Int] {
    if someNumber < 12 {
        31
    } else if someNumber == 19 {
        32
    } else {
        33
    }
}

var manualConditional: [Int]
if someNumber < 12 {
    let partialResult = ArrayBuilder.buildExpression(31)
    let outerPartialResult = ArrayBuilder.buildEither(first: partialResult)
    manualConditional = ArrayBuilder.buildEither(first: outerPartialResult)
} else if someNumber == 19 {
    let partialResult = ArrayBuilder.buildExpression(32)
    let outerPartialResult = ArrayBuilder.buildEither(second: partialResult)
    manualConditional = ArrayBuilder.buildEither(first: outerPartialResult)
} else {
    let partialResult = ArrayBuilder.buildExpression(33)
    manualConditional = ArrayBuilder.buildEither(second: partialResult)
}

I couldn't get from the proposed solution proposed solution how a tree is created, what are the nodes and leaves and why there is more than one call to specific "buildEither" in every block?

Thanks

1 Like

The calls are the intermediate nodes of the tree. The compiler sees these three blocks:

if condition_A {
  A
} else if condition_B {
  B
} else {
  C
}

or to rotate it:

  condition_A  condition_B     else
       A            B            C

There are three options here, but the compiler's only got the ability to express a choice between two options at a time, by calling either buildEither(first:) or buildEither(second:). So it has to make a tree of choices between two options:

  condition_A  condition_B     else
       A            B            C
        \          /            /
         \        /            /
         Either<A,B>          /
                 \           /
              Either<Either<A,B>,C>
4 Likes

Thank you very much for detailed explanation!