0

I'm trying to pass a view into a struct for creating a tab which is the following code:

struct TabItem: TabView {
    var tabView: View
    var tabText: String
    var tabIcon: String
    
    var body: some View {
        self.tabView.tabItem {
            Text(self.tabText)
            Image(systemName: self.tabIcon)
        }
    }
}

struct ContentView: View {
    var body: some View {
        NavigationView {
            TabView {
                TabItem(tabView: SimpleCalculatorView(), tabText: "Home", tabIcon: "house")
            }
        }
    }
}

The error I'm getting is the following:

Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements

1 Answer 1

1

The error says here is that the View protocol has associatedtype Body inside it and thus you can't use the View as a type. This means we have to provide more information about the expected type of the tabView. One of the solutions would be to use AnyView as a type, but that would require additional content wrapping into AnyView.

What I would suggest doing here instead of using AnyView is to let the compiler figure out the actual tabView type for you.

  1. Let's tell the compiler that we expect some type Content that confirms to the View protocol
  2. Additionally I don't really see the necessity of using TabView as part of the TabItem declaration. Try going with just View unless you have a strong reason for not doing so.
struct TabItem<Content: View>: View {   // Content is a type that we expect. `View` is used instead of `TabView` as it is in original code
    var tabView: Content                // Using Content instead of a View as it is an actual type now
    ...
}

The rest of the code can stay unmodified.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this worked. I've decided a better method is to just use a custom modifier on a View within the TabView since this leaves it as a basic view.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.