1

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.

2 Answers 2

1

nicksarno already answered but since you commented you didn't understand, I'll give it a shot.

$0 references the first argument in the current closure when they aren't named.

ForEach(pets, id: \.self) {
    // $0 here means the first argument of the ForEach closure
    NavigationLink(destination: Text($0)) {
        // $0 here means the first argument of the NavigationLink closure 
        // which doesn't exist so it doesn't work
        Text($0)
    }
}

The solution is to name the argument with <name> in

ForEach(pets, id: \.self) { pet in
    // now you can use pet instead of $0
    NavigationLink(destination: Text(pet)) {
        Text(pet)
    }
}

Note; The reason you get the weird error is because it finds a different NavigationLink init which does have a closure with an argument.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Why does a simple $0 not work as given in the question above?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.