Casting TupleView to AnyView array in SwiftUI

Issue

I’m trying to use a CustomTabView in a similar way to the native TabView and I’m getting the error Protocol type 'Any' cannot conform to 'View' because only concrete types can conform to protocols.

Possible Solution

I can solve this issue by passing in type erased views into CustomTabView like so:

CustomTabView {
    AnyView(Text("A"))
    AnyView(Text("B"))
    AnyView(Rectangle())
}

Desired Solution

Ideally, I’d like to be able to do the following just like the native TabView:

CustomTabView {
    Text("A")
    Text("B")
    Rectangle()
}

Question

How can I convert the TupleView into an array of AnyView so that I can use CustomTabView in the desired way?

You can use the buildArray function from the SwiftUI framework to convert the TupleView into an array of AnyView. Here’s an example:

extension View {
    func asAny() -> AnyView {
        AnyView(self)
    }
}

let views = buildArray {
    Text("A").asAny()
    Text("B").asAny()
    Rectangle().asAny()
}

You can then pass this views array into the CustomTabView like so:

CustomTabView(content: views)