Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result values in '? :' expression have mismatching types 'some View' and '...'

Tags:

swift

swiftui

I get this error when I’m trying to ternary the navigationBarItems to have various views:

Result values in '? :' expression have mismatching types 'some View' and 'ProfileImageBarButton'

@State var searchTapped: Bool = false

var body: some View {
    NavigationView {
        Text("lol")
            
   --> here i get the error .navigationBarItems(leading: searchTapped ? backButton : ProfileImageBarButton(showMenu: $showMenu))
        .navigationBarTitle(Text(""), displayMode: .inline)
    }.overlay(searchTextField)
}

private var backButton: some View {
    Image(systemName: "arrow.left")
        .foregroundColor(Color.blue)
        .onTapGesture {
            self.searchTapped = false
        }
}

This is ProfileImageBarButton:

struct ProfileImageBarButton: View {
    @Binding var showMenu: Bool
    
    var body: some View {
        Image(uiImage: UserDefaults.standard.getProfileImage()!)
            .resizable()
            .renderingMode(.original)
            .frame(width: 30, height: 30)
            .clipShape(Circle())
            .onTapGesture {
                self.showMenu.toggle()
            }
    }
}
like image 280
SwiftiSwift Avatar asked Aug 04 '19 01:08

SwiftiSwift


2 Answers

The error is telling you that, in an expression:

condition ? true_result : false_result

both true_result and false_result need to have the same type.

There are multiple ways to overcome this, here are two:

.navigationBarItems(leading: searchTapped ? AnyView(backButton) : AnyView(ProfileImageBarButton(showMenu: $showMenu)))

or

.navigationBarItems(leading: barItems())

...

func barItems() -> some View {
    return Group {
        if searchTapped {
            backButton
        } else {
            ProfileImageBarButton(showMenu: $showMenu)
        }
    }
}
like image 82
kontiki Avatar answered Nov 20 '22 11:11

kontiki


You can also use @ViewBuilder which allows you to put different views in its body:

.navigationBarItems(leading: barItems)
@ViewBuilder
var barItems: some View {
    if searchTapped {
        backButton
    } else {
        ProfileImageBarButton(showMenu: $showMenu)
    }
}
like image 43
pawello2222 Avatar answered Nov 20 '22 11:11

pawello2222