ios – Generic model extension with type restriction is not called


I have this generic Response which has a generic decodable element of type T. Adding an extension for a specific type is not getting called which is obvious. Is there any logic reason for this? Given that this is added in SPM.

Response.swift

struct Response<T: Decodable>: Decodable {
    let status: Bool
    let data: T
    let message: String
    
    // MARK: CodingKeys
    private enum CodingKeys: String, CodingKey {
        case status
        case data
        case message
    }
}

// This never gets called for type `EmptyResponse`
extension Response where T == EmptyResponse {
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        self.status = try container.decode(Bool.self, forKey: .status)
        self.message = try container.decode(String.self, forKey: .message)
        self.data = EmptyResponse()
    }
}

extension Response {
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        self.status = try container.decode(Bool.self, forKey: .status)
        self.message = try container.decode(String.self, forKey: .message)
        self.data = try (EmptyResponse() as? T) ?? container.decode(T.self, forKey: .data)
    }
}

EmptyResponse.swift

public struct EmptyResponse: Decodable {
}

As a workaround, casting is working fine

extension Response {
    ...
        self.data = try (EmptyResponse() as? T) ?? container.decode(T.self, forKey: .data)
    ...
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img