In the following code, I'm trying to create an array called recordsPlusOne with all items from an array inside the recordsViewModel (recordsViewModel.records) and one new record that needs to be created inside the RecordsView but I'm getting errors when I call recordsViewModel.records inside the init()
How can I create a new array with all items from an existing one plus one record that needs to be created inside the init() of the RecordsView?
Code:
struct RecordsView: View {
@ObservedObject var recordsViewModel: RecordsViewModel
private var recordsPlusOne: [Record] = []
init(){
let newRecord = Record()
recordsPlusOne = recordsViewModel.records // thows error 1
recordsPlusOne.append(newRecord)
}// thows error 2
var body: some View {
// some code to display the records
}
}
Error 1
Variable 'self.recordsViewModel' used before being initialized
Error 2
Return from initializer without initializing all stored properties
CodePudding user response:
It is possible to do if recordsViewModel will be injected via init arguments, like
init(vm: RecordsViewModel) { // << here !!
let newRecord = Record()
recordsPlusOne = vm.records // << pre-use !!
recordsPlusOne.append(newRecord)
recordsViewModel = vm // << initializing !!
}
