SwiftUI static builder not working with generics

Hi there,

I'm trying to build a static function to use it like a named initializer. This is not working because of the use of generics and looks like a compiler bug.

The static function can't infer the ParentContent. If I set the return type to ParentView<ChildView<StaticChildContent>> when using it on the LiveView, it can't infer the ParentContent either.
Also, if I add a constraint to the static function
where ParentContent == ChildView<StaticRowContent> it says, a same-type requirement error.
So looks like the generics are well constrained, but the compiler can't infer right the types.

If anybody has some help would be appreciated.

import SwiftUI

struct ChildView<ChildContent: View>: View {
    
    @ViewBuilder private var content: () -> ChildContent
    
    init(
        @ViewBuilder content: @escaping () -> ChildContent
    ) {
        self.content = content
    }
    
    
    var body: some View {
        VStack {
            content().padding()
        }
        .border(Color.blue)
    }
}

struct ParentView<ParentContent: View>: View {
    @ViewBuilder private var content: () -> ParentContent
    
    init(
        @ViewBuilder content: @escaping () -> ParentContent
    ) {
        self.content = content
    }
    
    var body: some View {
        VStack {
            content().padding()
        }
        .border(Color.red)
    }
}

extension ParentView {
    static func redBlue<StaticChildContent: View>(
        @ViewBuilder content: @escaping () -> StaticChildContent
    ) -> ParentView {
        ParentView {
            ChildView {
                content()
            }
        }
    }
}


struct LiveView: View {
    var body: some View {
        HStack {
            ParentView.redBlue {
                Text("Hello world")
            }
        }
    }
}

1 Like
Terms of Service

Privacy Policy

Cookie Policy