swift - SwiftUI 中的 ForEach 和 NavigationLink 问题
问题描述
这是我遇到问题的基本代码片段:
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")
}
}
我得到错误:
未能产生表达诊断;请提交错误报告
我在这里的目的是熟悉 NavigationLink,并导航到一个新页面,点击该项目时只显示文本。
任何帮助,将不胜感激。
解决方案
nicksarno 已经回答了,但既然你评论你不明白,我会试一试。
$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)
}
}
解决方案是将参数命名为<name> in
ForEach(pets, id: \.self) { pet in
// now you can use pet instead of $0
NavigationLink(destination: Text(pet)) {
Text(pet)
}
}
笔记; 你得到这个奇怪错误的原因是因为它找到了一个不同的 NavigationLink init,它确实有一个带参数的闭包。
推荐阅读
- python-3.x - 如何从文本文件中删除仅数字行?
- javascript - Chrome 配置文件 - 在几次页面重新加载后,编译后的代码多次加载到内存中
- arrays - 想要在选择下拉框列表后循环一个 json 数组
- java - 如何用java实现分页树结构?
- ios - SWRevealViewController 隐藏我的前视图控制器的导航栏
- c++ - 什么时候调用 std::thread 析构函数?
- vuejs2 - Vuex 未知动作类型...不会加载我的动作
- android - 应用程序包含可能导致路径遍历漏洞的不安全解压缩模式
- java - 使用 spring-boot @scheduled 注解同时执行两个调度器
- java - 如何在 servlet post() 控制器中获取反应 js 发布请求数据