swiftuiviewbuilder

@ViewBuilder function that has no return value


Does anyone know why when creating a viewBuider function that has no return value, it compiles and runs without any issue. In the example below "condition" is a Bool to determine to add a view or not.

@ViewBuilder private func viewSetup()->some View{

    if condition{
        Color(.yellow ).opacity(0.2)
    }
}

Solution

  • The ViewBuilder macro is basically a Result Builder. Result Builders allow to create a new value step by step passing in a sequence of our choice. For example, when you use a VStack you can slot in different views. Swift is capable of grouping them in a TupleView so that they can be stored as a single child in the VStack, effectively converting the sequence into a single view only.

    You can actually build your own result builder using the resultBuilder macro outside a struct. Each @resultBuilder must have at least one static function buildBlock(). By doing so you would end up with with a new Result Builder that you could use like so @YourStructName. More on this here: Result Builders.

    So, in SwiftUI, stricly speaking, the difference between using @ViewBuilder or not when returning some View is that when you don't use you have to treat that function as a standard one, always explicetely returning the return type you declared. When you use @ViewBulder instead, you tap in into SwiftUI hidden powers of decifering what's inside that function.