简体   繁体   English

SwiftUI 中的 ForEach 和 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.我在这里的目的是熟悉 NavigationLink,并导航到一个新页面,点击该项目时只显示文本。

Any help would be appreciated.任何帮助,将不胜感激。

nicksarno already answered but since you commented you didn't understand, I'll give it a shot. nicksarno 已经回答了,但既然你评论你不明白,我会试一试。

$0 references the first argument in the current closure when they aren't named. $0 在没有命名时引用当前闭包中的第一个参数。

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解决方案是用<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.你得到这个奇怪错误的原因是因为它找到了一个不同的 NavigationLink init,它确实有一个带参数的闭包。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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