swiftencodeencodable

Creating Encodable class by injecting class conforming only to Encodable protocol


I am building network module which uses Body class that will be encoded to serve as body of url request. I want to init Body with any class that is conforming to Encodable protocol, in my case it is MyDevice class conforming to DeviceEncodable, which is protocol defining everything that my url request needs. TheMyDevice class is already inheriting from another class called SpecialClass, therefore I can only conform it to protocol since swift does not allow inheritance from more than one class. The problem is that when I initialize Body with DeviceEncodable I get the Error "Type 'Body' does not conform to protocol 'Encodable'" I get it that it is because DeviceEncodable can be class but also some another protocol conforming to it. What is the correct solution to use DeviceEncodable as a property in Body function so it will be encoded properly and without need to inherit ? Here is Samble code:

    class Body: Encodable {
    let device: DeviceEncodable
    init(_ deviceInfo: DeviceEncodable) {
        self.device = deviceInfo
    }
}

protocol DeviceEncodable: AnyObject, Encodable  {
    var someSpecialProperty: String {get}
}

class MyDevice: SpecialClass, DeviceEncodable {
    var someSpecialProperty: String = "special"
}

class SpecialClass {
    var someOtherProperty: String = "other"
}

Solution

  • You cannot encode device because device must be a concrete type which conforms to Encodable. Possible solutions are an associated type of the protocol constrained to Encodable or a generic, something like

    class Body<T : Encodable> : Encodable {
        let device: T
    
        init(_ deviceInfo: T) {
            self.device = deviceInfo
        }
    }