Anyone successfully use a @ViewBuilder
for spouting out different destination views (conforming to a protocol) as an argument for the navigation link?
Re: conforming to a protocol -> ability to return an optional view; https://developer.apple.com/documentation/swiftui/viewbuilder/buildif(_:)
struct MyRoutesSectionViewObject: Hashable {
var title: String
var iconString: String
var count: Int
var badgeIconString: String?
}
protocol MyRoutesSectionViewControllerRepresentable {
var myRoutesSectionViewObject: MyRoutesSectionViewObject { get set }
}
enum Destination: CaseIterable, Hashable {
case savedRoutes
case plannedRoutes
case recordedRoutes
case offlineRoutes
}
// This obviously throws a compile error
struct MyRoutesSectionView: View {
var body: some View {
ForEach(Destination.allCases, id: \.self) { destination in
if let destinationView = self.destinationView(for: destination) as? MyRoutesSectionViewControllerRepresentable {
NavigationLink(destination: destinationView) {
MyRoutesNavigationLinkView(myRoutesObject: destinationView.myRoutesObject)
}
} else {
assert(false, "Destination view needs to conform to `MyRoutesSectionViewControllerRepresentable`")
return AnyView(EmptyView())
}
}
}
}
private extension MyRoutesSectionView {
@ViewBuilder
func destinationView(for destination: Destination) -> some View {
switch destination {
case .savedRoutes:
BMSavedRoutesView()
case .plannedRoutes:
BMPlannedRoutesView()
case .recordedRoutes:
BMRecordedRoutesView()
case .offlineRoutes:
BMOfflineRoutesView()
}
}
}