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
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()
}
}
}