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

SwiftUI中Unsafe Pointer错误:子视图无法正确引用枚举遍历index变量

问题分析与解决方案

错误直接原因

你在ContentView的Section中引用的index变量从未被定义——这里没有任何遍历循环(比如ForEach)生成index,直接使用index自然会报错。

设计逻辑问题

你的DisplayRow视图设计完全偏离需求:它内部封装了一个List,但你却试图给它传递单个枚举值的name/code/value,这会导致DisplayRow循环生成counter个完全相同的行,同时还会在ContentView的List里嵌套另一个List,既不符合“可复用子视图显示单行数据”的需求,也违背了SwiftUI的视图层级设计逻辑。

修正方案

1. 重构DisplayRow为单行视图

让它只负责渲染单一行数据,移除内部的List和counter参数:

struct DisplayRow: View {
    var name: String
    var code: String
    var value: Double
    
    var body: some View {
        VStack {
            HStack {
                Text(name)
                Text(code)
            }
            Text("$\(value)")
        }
    }
}

2. 在ContentView中遍历枚举生成行

在Section内部用ForEach遍历枚举数组,给每个DisplayRow传递对应索引的枚举值:

struct ContentView: View {
    var body: some View {
        List {
            Section(header: Text("Wounds")) {
                DisplayWoundRow()
            }
            Section(header: Text("Debride")) {
                // 遍历枚举数组的索引,生成对应行
                ForEach(0..<debride.allCases.count, id: \.self) { index in
                    DisplayRow(
                        name: debride.allCases[index].rawValue,
                        code: debridecode.allCases[index].rawValue,
                        value: debridevalue.allCases[index].rawValue
                    )
                }
            }
        }
    }
}

3. 更优雅的封装(可选)

如果三个枚举的元素数量始终一致,建议把对应数据封装成一个结构体,避免索引遍历的潜在问题:

// 假设你的枚举类型分别是Debride、DebrideCode、DebrideValue
struct DebrideItem {
    let name: String
    let code: String
    let value: Double
    
    init(debride: Debride, code: DebrideCode, value: DebrideValue) {
        self.name = debride.rawValue
        self.code = code.rawValue
        self.value = value.rawValue
    }
}

// 自定义zip3函数,用于同时遍历三个数组
func zip3<A, B, C>(_ a: [A], _ b: [B], _ c: [C]) -> [(A, B, C)] {
    let count = min(a.count, b.count, c.count)
    return (0..<count).map { (a[$0], b[$0], c[$0]) }
}

struct ContentView: View {
    // 预生成所有DebrideItem
    private let debrideItems = zip3(Debride.allCases, DebrideCode.allCases, DebrideValue.allCases)
        .map(DebrideItem.init)
    
    var body: some View {
        List {
            Section(header: Text("Wounds")) {
                DisplayWoundRow()
            }
            Section(header: Text("Debride")) {
                ForEach(debrideItems, id: \.name) { item in
                    DisplayRow(name: item.name, code: item.code, value: item.value)
                }
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Amar Cheema

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 04:24:17