我必须通过读取JSON文件来初始化值,因此编写了可用的initiazer。请查看以下代码并提供建议
struct ViewModel {
var cards : EmployeeData
init?() {
if let path = Bundle.main.path(forResource: "EmployeeData", ofType: "json") {
do {
let jsonData = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let decoder = JSONDecoder()
self.cards = try decoder.decode(EmployeeData.self, from: jsonData)
}
catch {
print(error.localizedDescription)
return nil
}
}
}
}
struct EmployeeData : Decodable {
var employeeCards : [EmployeeCards]
struct EmployeeCards : Decodable {
var title : String
var description : String
}
}