In future, it might be helpful to give your actual use case up front
If I understand the problem, you'd like the compiler to warn you if you've failed to handle one of a specific list of possibilities, and you want those possibilities to be known as a static type without using an existential box.
In order to do that, you'd have to give the compiler an exhaustive list somewhere. If SwiftUI vended a struct OneOf<...>: View
type for public use, then you could do what @Joe_Groff outlined. That is, you could make a protocol requirement produce() -> OneOf<...>
, giving an exhaustive list of conforming types inside the angle brackets, and then call that function from your @ViewBuilder body
.
However, SwiftUI doesn't want you spelling out its _ConditionalContent
type like that. So you'd need some other way of telling the compiler about your exhaustive list. I haven't worked through the example entirely, but unless I'm mistaken, one viable way in which you could do that is to make an internal enum of all the conforming types:
enum _E {
case p1(P1)
case p2(P2)
case p3(P3)
case p4(P4)
}
You can make _E
conform to View
and switch over all the cases exhaustively inside _E
's implementation of var body: some View
, then make produce() -> _E
a protocol requirement of P
which you can then use as @Joe_Groff demonstrates above.
You'd end up with a bit of boilerplate, but I believe it fulfills your requirements.