Search code examples
iosswiftequatable

Equatable == function implemented but still crashes


In my app, I have a class Video which implements the Equatable protocol because I need to use the ==(lhs:,rhs:) -> Bool function. My class was as this :

class Video: Equatable {
    var url: URL!
    // Some other vars
}

func ==(lhs: Video, rhs: Video) -> Bool {
    return lhs.url == rhs.url
}

It always worked for me but some users had crashes with the reason protocol witness for static Equatable.== infix(A, A) -> Bool in conformance Video.

So I tried another way to implement this function which is

class Video {
    var url: URL!
    // Some other vars
}

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

But the crashes still occur for some users and I don't understand why... Does someone already had this issue or know how to solve it?


Solution

  • Since your url can be nil you have to consider this case in the implementation of ==

    func ==(lhs: Video, rhs: Video) -> Bool {
        guard let lURL = lhs.url, let rURL = rhs.url else { return false }
        return lURL == rURL
    }
    

    If your design treats two objects with both nil urls as equal you have to add this case, too.