Bigair
Bigair

Reputation: 1592

Inheriting codable class raises error "required' initializer"

I inherited Codable class like below.

class Vehicle: Codable {
    let id: Int
    let name: String
    
    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
}

class Car: Vehicle {
    let type: String
    
    init(id: Int, name: String, type: String) {
        self.type = type
        super.init(id: id, name: name)
    }
}

And it shows error

'required' initializer 'init(from:)' must be provided by subclass of 'Vehicle'

What is a proper way to inherit codable class?

Upvotes: 0

Views: 571

Answers (1)

McNail
McNail

Reputation: 100

If you allow Xcode to fix the issue, it adds this method to the subclass:

required init(from decoder: Decoder) throws {
    fatalError("init(from:) has not been implemented")
}

Upvotes: 1

Related Questions