After watching this years Demystifying SwiftUI session I revisited my project for usage of AnyView
. A common pattern that I used was using AnyView
at the screen boundary to allow dynamic routing.
Screen boundaries are for me new views that are modally presented or pushed in navigation stacks for example.
So a common pattern in my code base looks like this
class FooPresenter {
@Published var isPresenting = false
@Published var presentedView: AnyView
}
struct FooView {
@StateObject var presenter = FooPresenter()
var body: some View {
Text("hello")
.sheet(isPresented: $presenter.isPresenting) {
presenter.presentedView
}
}
}
Now I understand that SwiftUI uses the type system to diff views, animate and more. And I can fully understand that on a single screen it is advisable to use as few AnyView
s as possible. However I am wondering is there a performance difference when using it across screen boundaries? Furthermore, is the SwiftUI system "resetting" its type data at AnyView
and then can do it's normal diffing until the next AnyView
. Something like this
- RootView
- Text
- Button
- SheetPresentation
- AnyView
- Text
- Button
- AnyView