Why does Xcode warn for using ViewBuilder with a return statement?

I'm using @ViewBuilder so I will be allowed to use statements that unwrap values within my views. But I also like to return the body of the view in a return statement, so I can run other code before view code is run.

Like this:

@ViewBuilder
var body: some View {
// do some stuff here like set variables differently for iOS and macOS, load different view conditionally based on settings etc…
    return VStack { // compiler warning: "Application of result builder 'ViewBuilder' disabled by explicit 'return' statement"
        // etc etc…
    }
}

So this builds and appears to work fine, but I get a compiler warning that says "Application of result builder 'ViewBuilder' disabled by explicit 'return' statement"

If I apply either of the fixes it suggests, it breaks my code with errors so it can't compile.

I don't understand what the problem is. What does it mean that it's "disabled" when its accomplishing my purpose for using @ViewBuilder just fine? Is there a better way to run the code I want to run before the view?

Replies

The implementation of ViewBuilder relies on the @resultBuilder attribute.

These articles provide a good overview of result builders:

  • https://www.hackingwithswift.com/swift/5.4/result-builders
  • https://www.avanderlee.com/swift/result-builders

This is why you can't explicitly return a value.


Something like this will work:

@ViewBuilder var osText: some View {
    #if os(iOS)
    let os = "iOS"
    #elseif os(macOS)
    let os = "macOS"
    #endif

    let str = "You are on \(os)"

    Text(str)
}


Adding the return keyword results in this warning:

Application of result builder 'ViewBuilder' disabled by explicit 'return' statement

This means that the @ViewBuilder won't do anything. You need to remove return to restore the desired behaviour.


If I apply either of the fixes it suggests, it breaks my code with errors so it can't compile.

This must be to do with the code you are running beforehand, as in my example performing either of the fixes complies cleanly. Can you show this code you are running?


Note: The body property of View is already marked with @ViewBuilder so there is no need to add it yourself.