AnyView needed to wrap @ViewBuilder if Protocol Extension

Hi everyone. I have a polite request to see if I am missing anything here.
I am aware this has been discussed before (so sorry for the dupe)....

I have a playground snippet to reproduce the problem. If anyone sees a easy workaround other than AnyView(), please let me know.

Thank you

import SwiftUI

protocol RandomThingProtocol {
    var bool: Bool { get }
}

struct MainView<Content: View>: View {
    let viewBuilder: Content
    var body: some View {
        viewBuilder
    }
}

struct EnclosingView: View {
    
    let something: RandomThingProtocol = RandomThing(bool: true)
    
    var body: some View {
        MainView(
            viewBuilder: something.viewBuilder()
        )
    }
}

struct RandomThing: RandomThingProtocol {
    let bool: Bool
}

extension RandomThingProtocol {
    @ViewBuilder
    func viewBuilder() -> some View {
        if bool {
            Text("")
        } else {
            EmptyView()
        }
    }
}

1 Like