Search code examples
swiftuiswiftui-navigationlink

How to create a factory method for NavigationLink in SwiftUI?


I would like to create a factory method for NavigationLink:s as follows:

func makeNavigationLink(label: String, destination: View) -> some View {
    NavigationLink(destination: StatsView(), label: {
        Text(label)
            .foregroundColor(.white)
            .font(.title)
    })
}

This produces an error: Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements

How should this be coded?


Solution

  • Add view constraint.

    func makeNavigationLink<Destination: View>(label: String, destination: Destination) -> some View {
            NavigationLink(destination: StatsView(), label: {
                Text(label)
                    .foregroundColor(.white)
                    .font(.title)
            })
        }