Search code examples
swiftsequenceswift4.1xcode9.3anyobject

Binary operator '===' cannot be applied to operands of type 'Self.Element' and 'AnyObject'


I get the following error: Binary operator '===' cannot be applied to operands of type 'Self.Element' and 'AnyObject' on the line: return contains { $0 === object }.

Is there a way to cast object to the type of Iterator.Element? Does the line where Iterator.Element: AnyObject not mean that that the Iterator.Element must be representable as AnyObject?

extension Sequence where Iterator.Element: AnyObject {

    /**
     - Parameter object:
     */
    func containsObjectIdentical(to object: AnyObject) -> Bool {
        return contains { $0 === object }
    }

}

Thanks for any help on this matter.


Solution

  • This is a bug SR-7275 (actually a regression). It should be already fixed in Xcode 9.3.1.

    Just remove the Iterator from the where clause:

    extension Sequence where Element: AnyObject {
        func containsObjectIdentical(to object: AnyObject) -> Bool {
            return contains { $0 === object }
        }
    }
    

    While Self.Element and Self.Iterator.Element for Sequence are the same, it seems the compiler cannot see the transitive equality.

    Also, you might consider making the method type safe and only compare with objects of type Element:

    extension Sequence where Element: AnyObject {
        func containsObjectIdentical(to object: Element) -> Bool {
            return contains { $0 === object }
        }
    }