Saranjith
Saranjith

Reputation: 11567

Confirm to Equatable for Custom struct

I have below kind of response model, where the body is decided by another variable. How can i confirm equatable to this Model

public struct Model {
    let type: String? // can be type1 or type2
    let body: ResponseType?
}

protocol ResponseType: Codable {

}


struct Response1: ResponseType {
    var items: [String]?
}


struct Response2: ResponseType {
    var item: String?
}

What i want to achive:

 extension Model: Equatable {
    public static func == (lhs: Model, rhs: Model) -> Bool {
        // How to equate the body?
    }
}

When im trying to add Equatable to ResponseType protocol it says below error. Protocol 'ResponseType' can only be used as a generic constraint because it has Self or associated type requirements

Upvotes: 1

Views: 282

Answers (1)

Sweeper
Sweeper

Reputation: 271895

You need to implement == manually. swift doesn't know that body can only be two types, which are?

public struct Model: Equatable {
    public static func == (lhs: Model, rhs: Model) -> Bool {
        if lhs.type != rhs.type {
            return false
        }
        if let lhsBody = lhs.body as? Response1, let rhsBody = rhs.body as? Response1 {
            return lhsBody == rhsBody
        } else if let lhsBody = lhs.body as? Response2, let rhsBody = rhs.body as? Response2 {
            return lhsBody == rhsBody
        } else {
            return false
        }
    }
    
    let type: String? // can be type1 or type2
    let body: ResponseType?
}

protocol ResponseType: Codable {

}


struct Response1: ResponseType, Equatable {
    var items: [String]?
}


struct Response2: ResponseType, Equatable {
    var item: String?
}

It might be easier if you change Model into an enum:

enum Model: Codable, Equatable {
    case type1(items: [String]?)
    case type2(item: String)

    var type: String {
        switch self {
        case .type1: return "type1"
        case .type2: return "type2"
        }
    }
}

You probably need to change the Codable implementation so that it encodes and decodes the way you want to.

Upvotes: 1

Related Questions