Any info on the _typeEraser attribute

The purpose of the @_typeEraser attribute is to allow functions with opaque return types constrained by certain protocols to be dynamically replaced with implementations that have different underlying types. Normally, if you write something like:

var body: some View { MyView() }

then the underlying type of body is fixed to MyView. Even if body is tagged dynamic, then @_dynamicReplacements for the body would still have to return the same MyView type in order to remain compatible. This is too restrictive for Xcode Previews, where we want users to be able to modify their SwiftUI views arbitrarily, and dynamically reload the new implementation in place. So, if the protocol constraint on a dynamic declaration's opaque type has an associated @_typeEraser, we use that @_typeEraser to implicitly wrap the opaque return type, so that even though you wrote MyView() above, the implementation is compiled as:

dynamic var body: some View { AnyView(MyView()) }

So the underlying type of the opaque type is AnyView. If you later modify body to return TheirView() instead, it will also be wrapped in AnyView, so the underlying type of the opaque type is not changed.

18 Likes