Search code examples
iosswiftequatable

Protocol conforming to Equatable for Diffing


I have a small chat app here.

I can have 2 types of messages: - text - video

I am using polymorphism while decoding the JSON like so:

import Foundation

enum MessageType: Int, Decodable {
    case text
    case video
}

protocol Message: Decodable {
    static var type: MessageType { get }
    var id: String { get }
    var user: User { get}
    var timestamp: String { get }
}

struct TextMessage: Message {
    static var type: MessageType = .text
    var id: String
    var user: User
    var timestamp: String
    let text: String
}

struct VideoMessage: Message {
    static var type: MessageType = .video
    var id: String
    var user: User
    var timestamp: String
    let text: String
    let link: String
    let poster: String
}

enum MessageWrapper: Decodable {

    enum CodingKeys: String, CodingKey {
        case type
    }

    case text(TextMessage)
    case video(VideoMessage)

    var item: Message {
        switch self {
        case .text(let item): return item
        case .video(let item): return item
        }
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        let type = try values.decode(Int.self, forKey: .type)
        switch type {
        case MessageType.text.rawValue: self = .text(try TextMessage(from: decoder))
        case MessageType.video.rawValue: self = .video(try VideoMessage(from: decoder))
        default:
            throw DecodingError.dataCorruptedError(forKey: .type,
                                                   in: values,
                                                   debugDescription: "Invalid type")
        }
    }
}

I am also using the MVVM approach like so:

struct ChatViewModel {

    enum ViewModelType {
        case loading
        case text(TextMessageViewModel)
        case video(VideoMessageViewModel)
        case failure(ErrorViewModel)
    }

    enum State {
        case initialized
        case loading
        case loaded([Message])
        case failed(Error)
    }

    let state: State
    let viewModels: [ViewModelType]

    init(with state: State) {
        self.state = state
        switch state {
        case .initialized:
            viewModels = []
        case .loading:
            viewModels = [
                .loading,
            ]
        ......
    }
}

In order to be able to use a Diffing library like Differ, the ChatViewModel should conform to the Equatable protocol.

extension ChatViewModel: Equatable {
    static func == (lhs: ChatViewModel, rhs: ChatViewModel) -> Bool {
        return lhs.state == rhs.state
    }
}

extension ChatViewModel.State: Equatable {
    static func == (lhs: ChatViewModel.State, rhs: ChatViewModel.State) -> Bool {
        switch (lhs, rhs) {
            case (.initialized, .initialized): return true
            case (.loading, .loading): return true
            case let (.loaded(l), .loaded(r)): return l == r
            case let (.failed(l), .failed(r)): return l.localizedDescription == r.localizedDescription
            default: return false
        }
    }
}

The problem here is for the case let (.loaded(l), .loaded(r)): return l == r, Message, as a protocol, doesn't conform to Equatable.

Making it conform to Equatable like

protocol Message: Decodable, Equatable {
    static var type: MessageType { get }
    var id: String { get }
    var user: User { get}
    var timestamp: String { get }
}

produce an error Protocol 'Message' can only be used as a generic constraint because it has Self or associated type requirements for the MessageWrapper:

enum MessageWrapper: Decodable {

    ...

    var item: Message { // Protocol 'Message' can only be used as a generic constraint because it has Self or associated type requirements
        switch self {
        case .text(let item): return item
        case .video(let item): return item
        }
    }

    ...
}

Any idea or suggestion to have a clean way to solve this? I saw some post about Type Erasure but after some tests I am not sure that it is actually solving the problem.


Solution

  • You don't have to conform to Equatable in order to be able to use the == operator. You can just define an operator like that yourself, without conforming to Equatable.

    For convenience's sake, I'll assume that TextMessage and VideoMessage already conforms to Equatable.

    First, write a method that compares Messages:

    func messageEqual(m1: Message, m2: Message) -> Bool {
        if let textMessage1 = m1 as? TextMessage, let textMessage2 = m2 as? TextMessage {
            return textMessage1 == textMessage2
        }
        if let videoMessage1 = m1 as? VideoMessage, let videoMessage2 = m2 as? VideoMessage {
            return videoMessage1 == videoMessage2
        }
        return false
    }
    

    Then a the == operator for [Message]:

    func ==(messages1: [Message], messages2: [Message]) -> Bool {
        return messages1.count == messages2.count && 
            zip(messages1, messages2).allSatisfy(messageEqual)
    }
    

    Now l == r should compile.