ForEach循环触发Thread 1: Index out of range错误求助
问题分析与解决方案
错误原因
你遇到的「Index out of range」错误,核心是ForEach循环的索引范围超出了数组的有效边界:
- 数组
boxNumberIdentificatie的元素个数为count,有效索引范围是0到count-1 - 你使用了闭区间
0...aantal(aantal等于数组count),这会让循环变量i取到count这个值,而数组不存在该索引位置,直接触发越界错误
修复代码
把闭区间...替换成半开区间..<,确保循环只遍历数组的有效索引:
@Published var boxNumberIdentificatie: [String] = [""] // 建议改为计算属性,避免数组变化时数值不更新 var aantal: Int { routesData.boxNumberIdentificatie.count } ForEach(0..<aantal, id: \.self){i in Section(header: Text("BoxIdentificatie (\(i))")) { TextField("", text: $routesData.boxNumberIdentificatie[i]) .font(isMacOS() ? .title3 : .body) } }
更安全的写法(推荐)
直接遍历数组的枚举序列(enumerated()),彻底避免手动管理索引的风险:
ForEach(Array(routesData.boxNumberIdentificatie.enumerated()), id: \.offset) { index, _ in Section(header: Text("BoxIdentificatie (\(index))")) { TextField("", text: $routesData.boxNumberIdentificatie[index]) .font(isMacOS() ? .title3 : .body) } }
额外注意事项
- 如果需要动态添加/删除文本框,确保数组操作逻辑在主线程执行(SwiftUI状态更新必须在主线程)
- 提交表单时若有修改数组的操作,要保证循环索引范围与数组实时状态匹配,避免异步操作导致的数组长度变化
内容的提问来源于stack exchange,提问作者BouBal
相关产品推荐
相关产品推荐

