Search code examples
swiftlistforeachswiftuiswiftui-navigationlink

Problem with ForEach and NavigationLink in SwiftUI


Here is a basic code snippet that I'm having problems with:

import SwiftUI

struct ContentView: View {
    var pets = ["Dog", "Cat", "Rabbit"]
    var body: some View {
    NavigationView {
        List {
            ForEach(pets, id: \.self) {
                NavigationLink(destination: Text($0)) {
                    Text($0)
                }
            }
        }
        .navigationBarTitle("Pets")
    }
}

I get the error:

Failed to produce diagnostic for expression; please file a bug report

My intention here was to get comfortable with NavigationLink, and navigate to a new page displaying just text on click of the item.

Any help would be appreciated.


Solution

  • It has something to do with the shorthand initializers that you are using. Either of these alternatives will work:

    ForEach(pets, id: \.self) {
         NavigationLink($0, destination: Text($0))
    }
    
    ForEach(pets, id: \.self) { pet in
         NavigationLink(destination: Text(pet)) {
              Text(pet)
         }
    }