-
Type erasure is the process of hiding the underlying type of some data.
- This is used often in Swift: we have type erasing wrappers such as
AnyHashable
andAnySequence
, and all they do is act as shells that forward on their operations to whatever they contain, without revealing what the contents are to anything externally.
- This is used often in Swift: we have type erasing wrappers such as
-
In SwiftUI we have
AnyView
for this purpose: it can hold any kind of view inside it- There is a performance cost to using
AnyView
: by hiding the way our views are structured, we’re forcing SwiftUI to do a lot more work when our view hierarchy changes
- There is a performance cost to using
-
Group
in an alternative that works in some situations. -
You CANNOT make an array of
Group
, but you CAN make an array ofAnyView
-
If you intend to use type erasure regularly, it’s worth adding this convenience extension:
extension View {
func erasedToAnyView() -> AnyView {
AnyView(self)
}
}
- With this approach we can treat erasedToAnyView() like a modifier:
Text("Hello World")
.font(.title)
.erasedToAnyView()
- Codable has flags for things like
.convertFromSnakeCase