'不能在不可变值上使用可变 getter:'self' 在迭代时是不可变的? [英] 'Cannot use mutating getter on immutable value: 'self' is immutable' when iterating?
问题描述
有谁知道为什么 ForEach
中的 self.indexCount
会给出错误 Cannot use mutating getter on immutable value: 'self' is immutable代码>错误?我可以提供
aView
和 indexCount
,但不是很方便.我没有改变 indexCount.这是 SwiftUI 错误还是故意的?
Does anyone know why the self.indexCount
in the ForEach
is giving the error Cannot use mutating getter on immutable value: 'self' is immutable
error? I can provide aView
with indexCount
, but it's not very convenient. I'm not changing indexCount. Is this a SwiftUI bug or intentional?
struct aView: View {
let array: [[String]]
lazy var indexCount: Int = array[0].count
var body: some View {
VStack {
ForEach(0..<self.indexCount, id: \.self) { index in
Text("Hello World")
}
}
}
}
推荐答案
这是故意的.在 SwiftUI 中,只有 @State
变量可以更改.你不能像那样使用 lazy var
.用计算属性替换它:
It's intentional. In SwiftUI, only @State
variables can change. You can't use a lazy var
like that. Replace it with a computed property:
var indexCount : Int { array[0].count }
无论如何这更好,因为它总是正确的:indexCount
将始终是 array[0]
的 current 大小),而您的方式,无论count
是第一次获取时,该值都会冻结.
That's better anyway, because it will always be correct: indexCount
will always be the current size of array[0]
), whereas your way, the value will freeze at whatever the count
is the first time it is fetched.
这篇关于'不能在不可变值上使用可变 getter:'self' 在迭代时是不可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!