You need to enable JavaScript to run this app. SwiftUI中绑定数组视图里TextField搭配onDelete触发索引越界问题
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中绑定数组视图里TextField搭配onDelete触发索引越界问题

SwiftUI onDelete 索引越界崩溃问题梳理

问题现象

  • 完全相同的删除逻辑,在只读展示的列表视图中可正常运行,在带金额编辑功能的跳转视图中触发崩溃,报错为数组下标越界
  • 排查确认:注释掉和$funds[index].balance绑定的TextField组件后,删除功能可正常运行

对应代码实现

可正常运行的主视图

状态声明:

@State var funds: [Account.Fund] = []

列表渲染与删除逻辑:

if funds.count > 0 {
    ForEach(funds.indices, id: \.self) { index in
        StandardRowView(word: funds[index].name, number: funds[index].balance)
    }
    .onDelete(perform: { indexSet in
        funds.remove(atOffsets: indexSet)
    })
}

跳转传值:

NavigationLink(
    destination: AddFundView(funds: $funds, savingsBalance: $balance),
    label: { Text("Funds") }
)

触发崩溃的AddFundView

绑定属性声明:

@Binding var funds: [Account.Fund]

带编辑功能的列表逻辑:

ForEach(funds.indices, id: \.self) { index in
    HStack {
        Text(funds[index].name)
        Spacer()
        TextField("Amount", value: $funds[index].balance, formatter: NumberFormatter.currency)
            .keyboardType(.numbersAndPunctuation)
            .multilineTextAlignment(.trailing)
            .onChange(of: funds[index].balance, perform: { value in
                // 金额超出储蓄余额时重置基金余额
                if value > savingsBalance || fundsTotal > savingsBalance {
                    funds[index].balance = copy[index].balance
                }
            })
    }
}
.onDelete(perform: { indexSet in
    funds.remove(atOffsets: indexSet)
})

崩溃日志:

Swift/ContiguousArrayBuffer.swift:580: Fatal error: Index out of range
2021-04-23 20:06:56.400433-0400 WMMG[12180:9619685] Swift/ContiguousArrayBuffer.swift:580:     Fatal error: Index out of range

崩溃原因

  • AddFundView中的TextField持有了基于数组位置索引的绑定引用。执行删除操作移除数组元素时,旧索引对应的下标在新数组中已不存在,TextField在响应绑定状态变化时,会通过旧的索引访问数组元素,直接触发越界
  • 主视图中渲染的是只读文本组件,不会持有跨状态的位置索引绑定,数组更新后SwiftUI会直接基于新的索引集合重新渲染,因此不会触发同类越界问题
  • 本质问题是把动态变化的数组位置索引作为了视图的持久标识,在带状态绑定的可编辑列表中,位置索引会随元素增删失效,进而引发越界访问

修复参考方向

  • 让Account.Fund遵循Identifiable协议,为每个基金条目分配全局唯一的稳定标识,ForEach遍历数组时直接使用元素自身的id作为标识,不再依赖位置索引做视图匹配
  • 编辑金额的校验逻辑通过唯一id匹配对应条目,避免直接使用位置索引读取备份值
  • 删除操作执行后,等待列表完成刷新再触发余额校验逻辑,减少状态更新中途的索引访问

内容的提问来源于stack exchange,提问作者Joseph Kessler

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 16:54:08