Binary operator '!=' cannot be applied to two 'any P' operands

596 views Asked by At

I tried this piece of code:

import Foundation

protocol P: Equatable {}

class T {
    var p: any P
    
    init(_ pp: any P) {
        self.p = pp
    }
    
    func update(_ pp: any P) {
        if pp != p {
            p = pp
        }
    }
}

But I'm getting an error:

Binary operator '!=' cannot be applied to two 'any P' operands

Why is that and how can I solve this? Thank you for your help

1

There are 1 answers

0
AudioBubble On

You cannot equate existentials. You need one concrete Equatable type.

func update(_ p: any P) {
  if !self.p.equals(p) {
    self.p = p
  }
}
public extension Equatable {
  /// Equate with a value of unknown type.
  func equals(_ any: some Any) -> Bool {
    self == any as? Self
  }
}

This method relies on implicitly opening one of the existential operands, and unfortunately cannot be replicated by an operator (e.g. !=?) yet.