gpt4 book ai didi

swift - 无法在不可变值: 'self' is immutable error上使用变异 setter/getter

转载 作者:行者123 更新时间:2023-12-03 09:16:42 24 4
gpt4 key购买 nike

我正在尝试重用旧版的Swift代码,但收到错误消息“不能对不可变值使用变异getter:'self'是不可变错误”。 Xcode希望在功能之前添加“变异”,并提出通过“修复”来实现。因此错误在那里消失了,但仍然停留在“文本”语句中。

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

最佳答案

因为当您在结构内部调用x时,尚不清楚contentView本身是否可变。实际上,仅当将定义为var时,值类型才可变为

因此,在将其用于struct内部的builder函数之前,应将其包装为不可变值。

像这样:

func xValue() -> Double {
var mutatableSelf = self
return mutatableSelf.x
}

var body: some View {
VStack {
Text("\(xValue())")
}
}

关于swift - 无法在不可变值: 'self' is immutable error上使用变异 setter/getter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57316270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com