-1

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

John DoeDoe
  • 133
  • 1
  • 7
  • 3
    why are you using `any`? I'm not 100% if this will apply, but both Int and String are Equatable, but you can mix and match. Saying `any P` leaves open the possibility that you will equate two Types that can't be equated. – Zonker.in.Geneva Apr 20 '23 at 20:11
  • 1
    can you provide some background or context to what you are actually trying to do? That might help. – Zonker.in.Geneva Apr 20 '23 at 20:12
  • 1
    Does the protocol has any other meaning (functionality) than extending `Equatable`? – Joakim Danielson Apr 20 '23 at 20:27
  • What are you trying to implement? It'll help us know exactly what you want to do, instead of us making bad code which technically "works" in a certain specific way. – George Apr 20 '23 at 20:48
  • You don't need `Foundation` for this. –  Apr 20 '23 at 21:00

1 Answers1

1

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.