1

I am trying to make a NavigationLink and provide the destination in its init but I am receiving an error:

Type 'any View' cannot conform to 'View'

struct MenuButton: View {
    
    let iconName: String
    let destination: () -> any View
    
    var body: some View {

        NavigationLink { //Type 'any View' cannot conform to 'View'
            destination()
        } label: {
            Image(systemName: iconName)
                .foregroundColor(.pink)
                .padding()
        }
    }
}


struct MenuBar: View {
    
    var body: some View {
        HStack {
            MenuButton(iconName: "gearshape") {
                //providing destination here
                let user = User(firstName: "Mock", lastName: "Data", dateStarted: 142356345)
                return HomeView(viewModel: HomeViewModel(user: user))
            }
        }
    }
}

If I switch any View to some View in the destination declaration, I receive an error:

Property declares an opaque return type, but has no initializer expression from which to infer an underlying type

Vadim F.
  • 881
  • 9
  • 21

2 Answers2

-1

You just need to make MenuButton generic over some type (say V) that conforms to View:

struct MenuButton<V: View>: View {
    
    let iconName: String
    let destination: () -> V
    
    var body: some View {

        NavigationLink { 
            destination()
        } label: {
            Image(systemName: iconName)
                .foregroundColor(.pink)
                .padding()
        }
    }
}
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
-1

Another option I found is wrapping destination() in AnyView:

 struct MenuButton: View {
    
    let iconName: String
    let destination: () -> any View
    
    var body: some View {
        NavigationLink {
            AnyView(destination())
        } label: {
            Image(systemName: iconName)
                .foregroundColor(.pink)
                .padding()
        }
    }
}
Vadim F.
  • 881
  • 9
  • 21