0

Four errors:

enter image description here

I don't understand why these complier errors are occurring. Did I not initialize "name", "empNum", "birthdate" and "department"?

@MainActor class EmployeeViewModel: ObservableObject {
@Published var name = ""
@Published var empNum = ""
@Published var birthdate = Date(timeIntervalSince1970: 0)
@Published var dept = ""

init(name: String = "", empNum: String = "", birthdate: Date = Date(timeIntervalSince1970: 0), dept: String = "") {
    self.name = name
    self.empNum = empNum
    self.birthdate = birthdate
    self.dept = dept
    
}
@Published var userData: [Employee] = [
    Employee(name: name, empNum: empNum, birthdate: birthdate, department: dept) //ERRORs Here
    ]
}

Here is my data model:

struct Employee: Codable, Identifiable {
var id = UUID()
var birthdate = Date(timeIntervalSince1970: 0)
var name = ""
var empNum = "8675309"
var department = ""

init(id: UUID = UUID(), birthdate: Date = Date(timeIntervalSince1970: 0), name: String = "", empNum: String = "8675309", department: String = "") {
    self.id = id
    self.birthdate = birthdate
    self.name = name
    self.empNum = empNum
    self.department = department
}
}
  • move `Employee(name: name, empNum: empNum, birthdate: birthdate, department: dept) //ERRORs Here ]` in to the init – YodagamaHeshan Oct 26 '22 at 01:02
  • @Yodagama I don't understand. Can you be more explicit? – weekendwarrior Oct 26 '22 at 01:20
  • 2
    You refer to the other vars (name, empNum, etc..) when you create `Employee(...)`. This is the reason you get the error. If you `move` this into `init(...)`, then it is ok to do. So declare `@Published var userData: [Employee] = []`, then use `self.userData = [Employee(....)]` in the `init(...)`. However, doing all this duplication is not a good idea. – workingdog support Ukraine Oct 26 '22 at 01:37

0 Answers0