I have simple viewModel
:
final class EmployeeListViewModel: ObservableObject {
@Published var list = [Employee]()
init() {
// some request
self.list = [Employee, Employee]
}
}
And have a 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)
}
}
}
}
}
}
Error text:
Cannot use instance member 'viewModel' within property initializer; property initializers run before 'self' is available
I tried change it with 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)
}
}
}
}
}
}
But it also throws error:
'self' used before all stored properties are initialized
this throws on I call viewModel
on init()
How to solve it? @State i use for card view. There I simplified views for easy understand.