简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM