【发布时间】:2020-10-29 15:26:07
【问题描述】:
我有简单的viewModel:
final class EmployeeListViewModel: ObservableObject {
@Published var list = [Employee]()
init() {
// some request
self.list = [Employee, Employee]
}
}
还有一个view:
struct EmployeeView: View {
@ObservedObject var viewModel = EmployeeListViewModel()
@State private var showContents: [Bool] = Array(repeating: false, count: viewModel.list.count)// <- error throws here
var body: some View {
GeometryReader { fullView in
ScrollView {
VStack(spacing: 40) {
ForEach(self.viewModel.list) { employee in
Text(employee.firstName).foregroundColor(.black)
}
}
}
}
}
}
错误文本:
不能在属性初始化器中使用实例成员“viewModel”;属性初始化器在“self”可用之前运行
我尝试用init改变它:
struct EmployeeView: View {
@ObservedObject var viewModel = EmployeeListViewModel()
@State private var showContents: [Bool]
init() {
_showContents = State(initialValue: Array(repeating: false, count: viewModel.list.count)) // <- error
}
var body: some View {
GeometryReader { fullView in
ScrollView {
VStack(spacing: 40) {
ForEach(self.viewModel.list) { employee in
Text(employee.firstName).foregroundColor(.black)
}
}
}
}
}
}
但它也会抛出错误:
在所有存储属性初始化之前使用'self'
这引发了我在init()上调用viewModel
如何解决? @State 我用于卡片视图。为了便于理解,我简化了视图。
【问题讨论】:
-
使用
init或将变量声明为lazy。 -
@JoakimDanielson 我更新了问题。
init无法解决。或者我用错了 -
@JoakimDanielson 尝试将
init上的代码移动到onAppear它抛出Cannot assign to property: 'self' is immutable