ResultBuilder that does something in buildEither

I (think) I understand why buildEither(first:) and buildEither(second:) are necessary to transform the body of a result builder into a tree that accurately represents the conditional logic of the source. But in practice I’ve never once seen an implementation that wasn’t simply:

func buildEither(first component: Component) -> Component { component }
func buildEither(second component: Component) -> Component { component }

So I feel like there’s nuance I'm not quite getting. Does anyone have an example of a result builder that does something non-trivial with buildEither?

SwiftUI's ViewBuilder implements it like this:

extension ViewBuilder {
    public static func buildEither<
        TrueContent: View,
        FalseContent: View
    >(first: TrueContent) -> _ConditionalContent<TrueContent, FalseContent> {
        .init(storage: .trueContent(first))
    }

    public static func buildEither<
        TrueContent: View,
        FalseContent: View
    >(second: FalseContent) -> _ConditionalContent<TrueContent, FalseContent> {
        .init(storage: .falseContent(second))
    }
}

public struct _ConditionalContent<TrueContent, FalseContent> {
    enum Storage {
        case trueContent(TrueContent)
        case falseContent(FalseContent)
    }
    let storage: SwiftUI._ConditionalContent<TrueContent, FalseContent>.Storage
}

I copied those definitions from SwiftUI's .swiftinterface file, removed some extraneous bits, and cleaned up the formatting.

SwiftUI tracks whether the content came from the true branch or the false branch because the “path” to the view forms part of its identity for transitions and animations.

3 Likes