[Discussion] Default Generic Arguments

I often run into the need to duplicate initializers just to achieve default generic arguments:

struct ContainerView<Content: View>: View {
    var color: Color
    var content: Content

    init(
        color: Color, 
        @ViewBuilder content: () -> Content
    ) {
        self.color = color
        self.content = content()
    }

    init(color: Color) where Content == EmptyView {
        self.color = color
        self.content = EmptyView()
    }
}

When I try to simplify it into this:

struct ContainerView<Content: View>: View {
    var color: Color
    var content: Content

    init(
        color: Color,
        @ViewBuilder content: () -> Content = { EmptyView() } // error: Cannot convert value of type 'EmptyView' to closure result type 'Content'
    ) {
        self.color = color
        self.content = content()
    }
}

Is there any way the compiler could get smarter about this, or is it too complex of an ask?

7 Likes
Terms of Service

Privacy Policy

Cookie Policy