Swift官方iOS开发教程State Management章节DailyScrum无history成员报错求解
问题根因
你遇到的三类报错确实是同一原因导致的,核心有两个可能的遗漏点:
- 你当前视图中的
scrum变量是@Binding包装类型,直接读写属性时没有访问其包装的实际值 DailyScrum结构体中未定义history存储属性,导致属性访问不存在
修复步骤
步骤1:补全DailyScrum结构体定义
先打开你的DailyScrum.swift文件,确认结构体中已经添加了history属性,没有的话补上:
struct DailyScrum: Identifiable { // 原有属性:id、title、attendees、lengthInMinutes等保持不变 var history: [History] = [] // 新增这行,默认赋值为空数组 }
步骤2:修正Binding类型属性的访问方式
如果你当前视图里的scrum是用@Binding var scrum: DailyScrum声明的,在闭包内直接读写属性需要访问它的wrappedValue:
第一处onDisappear代码修正:
.onDisappear { scrumTimer.stopScrum() let newHistory = History(attendees: scrum.attendees, lengthInMinutes: scrumTimer.secondsElapsed / 60) scrum.wrappedValue.history.insert(newHistory, at: 0) }
第二处列表代码修正:
Section(header: Text("History")) { if scrum.wrappedValue.history.isEmpty { Label("No meeting yet", systemImage: "calendar.badge.exclamationmark") } ForEach(scrum.wrappedValue.history) { history in HStack { Image(systemName: "calendar") Text(history.date, style: .date) } } }
额外排查点
如果修改后还有报错,确认History结构体已经正确实现Identifiable协议,满足ForEach遍历的要求。
内容的提问来源于stack exchange,提问作者AUM 1127
相关产品推荐
相关产品推荐

