Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements

Viewed 6430

I'm trying to pass in a destination View Struct to another view, but the code won't compile.

I want to pass in some struct that conforms to the view protocol, so it can be used in a navigation button destination, but I can't seem to get it to compile. I've tried setting the type of destination to _View as well. Any suggestions are much appreciated.

struct AnimatingCard : View {

    var title, subtitle : String
    var color : Color
    var destination : View

    init(title : String, subtitle: String, color: Color, destination : View){
        self.title = title
        self.subtitle = subtitle
        self.color = color
        self.destination = destination


    }

    var body: some View {
        NavigationButton(destination: destination) {
    ...
        }
   }
}
1 Answers

If there’s no common concrete type that all the views used in destination will be, you should use the AnyView struct to obtain a type-erased concrete View conforming object.

ETA:

AnyView has an initializer declared as init<V>(_ view: V) where V : View, so wherever you were creating your AnimatingCard before you should now write:

AnimatingCard(title: title, subtitle: subtitle, color: color, destination: AnyView(view))

Alternatively, you could make AnimatingCard's initializer generic over all View-conforming types and do the AnyView conversion inside the initializer, like this:

init<V>(title : String, subtitle: String, color: Color, destination : V) where V: View {
    self.title = title
    self.subtitle = subtitle
    self.color = color
    self.destination = AnyView(destination)
}
Related