Search code examples
swiftobjectmapper

ObjectMapper - Initialize an empty init in child class


I have a base class called "Base" that implements the Mappable protocol. I already subclassing that class as described below.

class Base: Mappable {
    var base: String?

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        base <- map["base"]
    }
}

class Subclass: Base {
    var sub: String?

    required init?(map: Map) {
        super.init(map: map))
    }

    override func mapping(map: Map) {
        super.mapping(map: map)

        sub <- map["sub"]
    }
}

Is it possible to create an empty init in subclass that how i can create an instance of subclass like this?

var obj = Subclass()

Solution

  • You can add init() inside your Base and override init() inside your SubClass

    class Base: Mappable {
        var base: String?
    
        init() {}
    
        required init?(map: Map) {
    
        }
    
        func mapping(map: Map) {
            base <- map["base"]
        }
    }
    
    class Subclass: Base {
        var sub: String?
    
        override init() {
            super.init()
        }
    
        required init?(map: Map) {
            fatalError("init(map:) has not been implemented")
        }
    
        override func mapping(map: Map) {
            super.mapping(map: map)
    
            sub <- map["sub"]
        }
    }