0

How to use inheritance with Swift Codable protocol. When decoding Student & Employee data getting Super class (Human) properties nil.

Here is sample:

class Human: Codable {
    var age: Int?
    var name: String?
}

class Student: Human {
    var studentId: Int?
    var course: String?
}

class Employee: Human {
    var empId: Int?
    var department: String?
}

let studentDecoder = JSONDecoder()
if let result = try? studentDecoder.decode(Student.self, from: data) {
    print(result.name) // getting nil
    print(result.age) // getting nil
}

let employeeDecoder = JSONDecoder()
if let result = try? employeeDecoder.decode(Employee.self, from: data) {
    print(result.name) // getting nil
    print(result.age) // getting nil
}
  • I am not sure I understand what your question is in relation to the code you posted. – onnoweb Aug 08 '18 at 13:54
  • There is no *Automatic*. `Codable` is not able to synthesize inheritance. You have to write code as described in the duplicate. – vadian Aug 08 '18 at 17:17

0 Answers0