You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中使用ForEach循环遍历二维数组生成SwiftUI导航项的问题

问题原因

你原代码的问题在于直接将循环的索引值index当做内容传入,同时错误书写了self.index(self指向当前视图实例,不存在index属性),没有通过索引读取二维数组中存储的实际文本和图标名称。

修复方案

方案1:基于现有二维数组直接修改

直接通过索引从navigation数组中取出对应子数组,读取对应位置的内容即可:

let navigation = [["Kunde", "person"], ["Wartung", "gear"]]

NavigationView {
    List {
        ForEach(navigation.indices, id: \.self) { index in
            let item = navigation[index]
            NavigationLink(destination: ListView(title: item[0])) {
                Label(item[0], systemImage: item[1])
            }
        }
    }
}

方案2(推荐):用结构体优化类型安全

二维字符串数组的下标访问存在越界风险,类型也不明确,更推荐定义专属结构体存储导航项信息,代码更易维护也更安全:

// 定义导航项结构体,遵从Identifiable协议适配SwiftUI ForEach遍历规则
struct NavigationItem: Identifiable {
    let id = UUID()
    let title: String
    let systemIcon: String
}

// 替换原有二维数组
let navigation = [
    NavigationItem(title: "Kunde", systemIcon: "person"),
    NavigationItem(title: "Wartung", systemIcon: "gear")
]

// 视图层实现
NavigationView {
    List {
        ForEach(navigation) { item in
            NavigationLink(destination: ListView(title: item.title)) {
                Label(item.title, systemImage: item.systemIcon)
            }
        }
    }
}
注意事项
  • 如果导航数组是会动态变化的可变数组,不要直接使用navigation.indices遍历,否则可能出现索引不匹配的异常,使用Identifiable结构体的方案可以完全规避该问题
  • iOS 16+ 已经废弃NavigationView,推荐替换为NavigationStack或NavigationSplitView适配新系统特性

内容的提问来源于stack exchange,提问作者Nikolass。

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:36:04