0

I have to initialise values by reading from JSON file hence was writing failable initiazer. Please review following code and provide suggestions

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
        }
}
picciano
  • 22,341
  • 9
  • 69
  • 82
  • 1
    You must provide a branch for when `if let path` fails. – Eric Aya Apr 09 '18 at 15:02
  • A failable initializer is nonsense in this case. Files in the application bundle are required at compile time and cannot be changed at runtime. Use `try!` and force unwrap optionals. The code must not crash. If it does you made a design mistake. And there is a `url(forResource` API. – vadian Apr 09 '18 at 15:12
  • Adding fail branch to if let helped to get rid of compilation error. – Hrishikesh Devhare Apr 09 '18 at 15:33
  • Using url(forResource ) is clean solution for code at hand however failable initiazer is required to handle failure due to json parsing. – Hrishikesh Devhare Apr 09 '18 at 15:35
  • There are unit tests to evaluate the JSON parsing. That's clearly a compile / design time issue. You are discouraged from checking it at runtime – vadian Apr 09 '18 at 16:30

0 Answers0