Reputation: 115
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.
Upvotes: 1
Views: 1233
Reputation: 3687
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.
Upvotes: 1
Reputation: 4245
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)
}
}
Upvotes: 0