1

I am using UINavigationController under the hood for my SwiftUI application since NavigationView and NavigationLink are extremely limited and/or buggy. I have a function called pushView(..) that needs to take in a SwiftUI view, wrap it in UIHostingController and then push it on top of the navigation stack:

func pushView(view: AnyView, animated: Bool = true) {
    let hostingView = UIHostingController(rootView: view)
    navigationController.pushViewController(hostingView, animated: animated)
}

Now, most of my calls look like ...pushView(AnyView(MyView()), I have to cast every single view to AnyView which is a bit annoying and unclean.

Is there a better way to do this so I don't have to cast every single time?

Zorayr
  • 23,770
  • 8
  • 136
  • 129

1 Answers1

2

Generally, you'd need an AnyView to type-erase views if you want to collect them into some array (rare, for SwiftUI, and unless you know what you're doing, it's probably not the way to go), but here since all you're doing is pushing instances of UIViewControllers (which is what UIHostingController inherits from), you should be able to use a generic function:

func pushView<V: View>(view: V, animated: Bool = true) {
    let hostingView = UIHostingController(rootView: view)
    navigationController.pushViewController(hostingView, animated: animated)
}
pushView(view: MyView())
New Dev
  • 48,427
  • 12
  • 87
  • 129