swiftswiftuiviewbuilder

SwiftUI ViewBuilder can't pass in different views


In Swift/SwiftUI, I'm trying to make a custom view, which takes other views as arguments. However, I'm getting the error Type of expression is ambiguous without more context.

I know that this error is usually due to mismatching types. Also, in the implementation below, having 2 Text views causes no error, but using a Text view as well as an Image view causes an error.

This makes me believe that the error is due to the fact that Image and Text are technically different types. However, since they both conform to View, and because my CustomView has both parameters of type View, I don't understand why this issue is happening.

struct CustomView<Content: View>: View {
    @ViewBuilder var label: Content
    @ViewBuilder var content: Content

    var body: some View {
        VStack {
            self.label

            self.content
        }
    }
}


struct ContentView: View {
    var body: some View {
        CustomView {             //<-- ERROR: Type of expression is ambiguous without more context
            Image(systemName: "person.3.fill")
        } content: {
            Text("")
        }
    }
}

What am I doing wrong, and how can I fix this error? Thanks in advance!


Solution

  • The problem with your code is that in CustomView you defined both label and content as views of a single type (generic Content), but you pass different kinds to the initializer.

    One way to fix it is to define different types for label and content:

    struct CustomView<Label: View, Content: View>: View {
        @ViewBuilder let label: Label
        @ViewBuilder let content: Content
    
        // The rest is unchanged.