Categories
iOS Development

Cannot use explicit ‘return’ statement in the body of result builder ‘ViewBuilder’ fixing guide

And another post on how to fix crude Xcode or more specifically SwiftUI errors. Did you ever come across “Cannot use explicit ‘return’ statement in the body of result builder ‘ViewBuilder'”? I see it regularily and it’s actually not to big of a deal to fix it once you see what is usually causing it.

To me the value of debugging information of this specific error is as low as in this one I also wrote a post about https://mic.st/blog/swiftui-and-the-compiler-is-unable-to-type-check-this-expression-in-reasonable-time/. It basically reads like the compiler gave up and now it is your turn to find out where to look and what to look for.

Okay, now let’s see how to actually fix this.

The “Cannot use explicit ‘return’ statement in the body of result builder ‘ViewBuilder'” error in the wild. Or as seen inside of Xcode.

Wrong or not updated parameter in Previews

Previews are a great thing but you have to make sure of course they do also compile correctly. And here we already have the location to look for. Atl least in my case, it is in around 90% of all cases somewhere in the Previews I did not update.

For example let’s say you had a parameter that did have a parameter namedaccessibilyIDs expecting a special type containing accessibility identifiers.

You decided, “It is overengineered, I don’t need that anymore” and changed your initializer to accessibilyID with a basic String type.

Now, if you have a couple of Views created and returned inside of your #Preview macro it will just fail with “Cannot use explicit 'return' statement in the body of result builder 'ViewBuilder'” pointing to that specific line where the preview does return the View.

Conclusion

Similar to a lot of other Xcode errors, it is one of these where you just “have to know”. But as SwiftUI error handling got better over the years, I hope errors like this inside of previews will also get a little more easy to see at some point.

Leave a Reply

Your email address will not be published. Required fields are marked *

Privacy Overview
mic.st

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.