Swift中结构体实例存入静态变量数组失败:实例未被添加
问题排查:SwimmingWorkout实例无法添加到静态数组中
嘿,我看你在把SwimmingWorkout实例存入对应的静态数组时遇到了麻烦——实例没成功加进去对吧?先把你给出的代码补全并格式化,方便咱们定位问题:
struct SwimmingWorkout { let distance: Double // 单位:米 let time: Double // 单位:秒 let stroke: Stroke enum Stroke { case freestyle, butterfly, backstroke, breaststroke } static var freestyleWorkouts = [SwimmingWorkout]() static var butterflyWorkouts = [SwimmingWorkout]() static var backstrokeWorkouts = [SwimmingWorkout]() static var breaststrokeWorkouts = [SwimmingWorkout]() }
结合Swift的特性,我整理了几个最可能导致这个问题的原因,以及对应的解决办法:
1. 没有自动关联实例与数组的逻辑
你可能只是创建了实例,但没写代码把它加入对应数组——Swift不会自动帮你把实例归类到静态数组里。比如你如果只这么写:
let myFreestyle = SwimmingWorkout(distance: 500, time: 600, stroke: .freestyle)
这个实例只会存在于myFreestyle变量里,不会自动跑到freestyleWorkouts数组中。
解决办法:给结构体加个自定义初始化方法,创建实例时自动把它塞进对应数组:
struct SwimmingWorkout { // 原有属性、枚举不变 let distance: Double let time: Double let stroke: Stroke enum Stroke { case freestyle, butterfly, backstroke, breaststroke } static var freestyleWorkouts = [SwimmingWorkout]() static var butterflyWorkouts = [SwimmingWorkout]() static var backstrokeWorkouts = [SwimmingWorkout]() static var breaststrokeWorkouts = [SwimmingWorkout]() // 自定义初始化,自动归类到对应数组 init(distance: Double, time: Double, stroke: Stroke) { self.distance = distance self.time = time self.stroke = stroke // 根据泳姿添加到对应静态数组 switch stroke { case .freestyle: Self.freestyleWorkouts.append(self) case .butterfly: Self.butterflyWorkouts.append(self) case .backstroke: Self.backstrokeWorkouts.append(self) case .breaststroke: Self.breaststrokeWorkouts.append(self) } } }
现在创建实例后,数组里就会自动有这个记录了:
let testWorkout = SwimmingWorkout(distance: 500, time: 600, stroke: .freestyle) print(SwimmingWorkout.freestyleWorkouts.count) // 输出1,说明添加成功
2. 访问静态数组的方式错误
如果你手动写了添加代码,但可能搞错了访问方式——静态数组属于结构体本身,不是实例属性。比如你如果这么写:
// 错误:试图通过实例访问静态数组 myFreestyle.freestyleWorkouts.append(myFreestyle)
这会直接报错,因为freestyleWorkouts是SwimmingWorkout的静态属性,必须通过结构体名访问。
解决办法:用结构体名来访问静态数组:
// 正确写法 SwimmingWorkout.freestyleWorkouts.append(myFreestyle)
3. 数组被意外清空
如果你的代码里有其他地方重新初始化了静态数组(比如SwimmingWorkout.freestyleWorkouts = []),那之前添加的实例就会被清空,看起来像是没加进去。
解决办法:检查代码中是否有对静态数组的重新赋值操作,确保只有在需要清空的时候才这么做。
快速验证方法
添加实例后,直接打印数组的长度或者内容,就能确认是否添加成功:
print("自由泳训练记录数:\(SwimmingWorkout.freestyleWorkouts.count)") print("第一条自由泳记录:\(SwimmingWorkout.freestyleWorkouts.first ?? "无记录")")
内容的提问来源于stack exchange,提问作者andy.emmett
相关产品推荐
相关产品推荐

