How to implement an equatable protocol for a protocol based on the identity of two instances that implement this protocol?

I am trying to implement an equatable protocol for a protocol based on the left and right value of an operand. In other words: How to implement the Equatable protocol for a protocol to determine if two instances implementing this protocol are identical (in my case iNetworkSubscriber) (same object reference). For example (an error message is included in the code below):

protocol iNetworkSubscriber : Equatable {

    func onMessage(_ packet: NetworkPacket)

}

func ==(lhs: iNetworkSubscriber, rhs: iNetworkSubscriber) -> Bool {     // <- Protocol 'iNetworkSubscriber' can only be used as a generic constraint because it has Self or associated type requirements
    return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)               // <- Cannot invoke initializer for type 'ObjectIdentifier' with an argument list of type '(iNetworkSubscriber)'
}

... and I also tried it with the identification operator itself:

func ==(lhs: iNetworkSubscriber, rhs: iNetworkSubscriber) -> Bool {     // <- Protocol 'iNetworkSubscriber' can only be used as a generic constraint because it has Self or associated type requirements
    return lhs === rhs                                                  // <- Binary operator '===' cannot be applied to two 'iNetworkSubscriber' operands
}

Does anyone know how to solve this problem?

+4
source share
2 answers

. -, ObjectIdentifier . () :

protocol NetworkSubscriber : class, Equatable {
    func onMessage(_ packet: NetworkPacket)
}

(, i . Swift.)

. ( Self Equatable). , , , .

func ==<T: NetworkSubscriber>(lhs: T, rhs: T) -> Bool {
    return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}

, NetworkSubscriber , , . , . , .

+3

( , class). , class:

protocol NetworkSubscriber: class, Equatable {
    func onMessage(_ packet: NetworkPacket)
}

, === NetworkSubscriber ( ). ==, ===, ===, , , :

let ns1 = getNewNetworkSubscriber()
let ns2 = getNewNetworkSubscriber()
print(n1 === n2) // false
print(n1 === n1) // true
+2

Source: https://habr.com/ru/post/1692377/


All Articles