Swift Equatable on a protocol

前端 未结 10 2126
时光说笑
时光说笑 2021-01-30 12:42

I don\'t think this can be done but I\'ll ask anyway. I have a protocol:

protocol X {}

And a class:

class Y:X {}
10条回答
  •  温柔的废话
    2021-01-30 13:13

    You have to implement a protocol extension constrained to your class type. Inside that extension you should implement the Equatable operator.

    public protocol Protocolable: class, Equatable
    {
        // Other stuff here...
    }
    
    public extension Protocolable where Self: TheClass
    {
        public static func ==(lhs: Self, rhs:Self) -> Bool 
        {
            return lhs.name == rhs.name
        } 
    }
    
    
    public class TheClass: Protocolable
    {
        public var name: String
    
        public init(named name: String)
        {
            self.name = name
        }
    }
    
    let aClass: TheClass = TheClass(named: "Cars")
    let otherClass: TheClass = TheClass(named: "Wall-E")
    
    if aClass == otherClass
    {
        print("Equals")
    }
    else
    {
        print("Non Equals")
    }
    

    But let me recommend you add the operator implementation to your class. Keep It Simple ;-)

提交回复
热议问题