I have a problem when trying to user ternary operator on a button in NavigationLink. I have an array of campaigns, which is displayed in a carouselView. Bellow carousel there is a button(NavigationLink) for opening another view which displays details of the campaign. The array of campaigns is empty initially, so I have to check if self.cardCampaigns > 0, if that is true it should navigate to a view which displays details of the campaign, otherwise ignore( I am trying to show a view with text "No campaigns available". I am using ternary operator for that, but it's not working. I get "Result values in '? :' expression have mismatching types 'CampaignDetailsView' and 'Text'" error where I use ternary operator.
My code is bellow:
NavigationLink(destination:
self.cardCampaigns.count > 0 ? CampaignDetailsView(viewModel: CampaignDetailsViewModel(campaign: cardCampaigns[self.count].campaign)) : Text("No Campaign found")
) {
ZStack {
RoundedRectangle(cornerRadius: 8)
.foregroundColor(Color.orOrangeColor)
.frame(width: 300, height: 50)
Text("Details")
.foregroundColor(.white)
}
}
This is because the types of
CampaignDetailsView
andText
don't match. You need to use a@ViewBuilder
(or just aGroup
,VStack
etc).Here is a solution with the destination view as a
@ViewBuilder
computed property:Which you can use like this: