【发布时间】:2026-01-26 02:50:01
【问题描述】:
我正在尝试重用一段较旧的 Swift 代码,但出现错误“不能在不可变值上使用 mutating getter:'self' is immutable error”。 Xcode 想在 func 之前添加“变异”,并提出通过“修复”来实现。所以错误消失了,但仍然存在于“文本”语句中。
import SwiftUI
struct ContentView: View {
typealias PointTuple = (day: Double, mW: Double)
let points: [PointTuple] = [(0.0, 31.98), (1.0, 31.89), (2.0, 31.77), (4.0, 31.58), (6.0, 31.46)]
lazy var meanDays = points.reduce(0) { $0 + $1.0 } / Double(points.count)
lazy var meanMW = points.reduce(0) { $0 + $1.1 } / Double(points.count)
lazy var a = points.reduce(0) { $0 + ($1.day - meanDays) * ($1.mW - meanMW) }
lazy var b = points.reduce(0) { $0 + pow($1.day - meanDays, 2) }
lazy var m = a / b
lazy var c = meanMW - m * meanDays
lazy var x : Double = bG(day: 3.0)
lazy var y : Double = bG(day: 5.0)
lazy var z : Double = bG(day: 7.0)
mutating func bG(day: Double) -> Double {
return m * day + c
}
var body: some View {
VStack {
Text("\(x)")
Text("\(y)")
Text("\(z)")
}
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
【问题讨论】:
-
我发现这个问题的解决方法是使用计算属性而不是惰性变量。我不明白为什么我不能使用惰性变量,但我也不明白建议的解决方案
-
@charel-f 我写了一个新答案。请看一下
-
谢谢,您的新答案非常简洁易懂
标签: swift swiftui getter-setter getter computed-properties