"any View cannot conform to View"

Hello,

What is the solution to this problem, assuming that you are not supposed to use AnyView, which I hear over and over again?

Given this protocol:

protocol MyProtocol {
    associatedtype V: View
    var content: () -> V { get }
}

if I want to store a heterogenous collection of MyProtocol,

let collection: [any MyProtocol], 

then the underlying V type of each is erased to any View, which (supposedly) does not conform to View.

Is there no way to "unbox" the existential any View to get the underlying View back? That unboxing idea is something I heard in a few WWDC videos but it seems like it does not apply to View.

AnyView is fine to use if you actually want to erase the underlying type! In fact it's provided expressly for this purpose! Existentials (like any View) can't conform to their own protocol types, so SwiftUI provides a type eraser for you.

The only caveats about AnyView use:

If you can preserve static type information, that is always better! However, if you're trying to store a heterogenous collection, then that's likely not possible (unless you could maybe use a parameter pack for your purposes?)

Additionally, AnyView is not super performant if:

  • You are passing the AnyView directly to a List or lazy layout: Lazy containers have poor performance if they don't know the number of subviews produced by their content, and AnyView could produce any number of subviews! If you need to show type-erased content in a lazy container, wrap it in a layout like a VStack so it always produces one subview.
  • You are changing the underlying type of the AnyView: If the underlying type an AnyView erases doesn't change, its performance is not significantly different from normal views (outside of the lazy container case mentioned above). However every time the underlying type does change, SwitfUI needs to do a lot of work to tear down the view of the existing type, and set up a new view with the new type. Given that, you want to avoid changing the underlying type if at all possible.
"any View cannot conform to View"
 
 
Q