Custom equates operator

Hi,


I have a class that inherits from nsobject and I want to write a custom '==' operator for it. According to this

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html#//apple_ref/doc/uid/TP40014097-CH27-ID28

I should be able to just add:


    override func == (left: GPPlace, right: GPPlace) -> Bool {
        return (left.placeID == right.placeID)
    }


but all that piece of code gets me is:

GPPlace.swift:38:19: Operators are only allowed at global scope

GPPlace.swift:38:21: Consecutive declarations on a line must be separated by ';'

GPPlace.swift:38:22: Expected declaration

Answered by jawbroken in 69494022

From the first error it sounds like you are trying to declare that within the class. You need to define this in “global scope” as the error says, as these operator functions are not methods.

Accepted Answer

From the first error it sounds like you are trying to declare that within the class. You need to define this in “global scope” as the error says, as these operator functions are not methods.

Exactly, and because of that, override isn't applicable.


Namespace scope is appropriate for a small amount of things. I'm glad this is the way it's handled in Swift, instead of having them be static methods inside of types like in C#. I'd frequently have to drain cognitive resources deciding which of two types an operator was more releveant to, in that language.

I have a class that inherits from nsobject and I want to write a custom '==' operator for it.

If the class is derived from NSObject you’re probably better off overriding

-isEqual:
. That way, if the object ‘escapes’ into the Objective-C world (and that’s if not going to happen, why are you subclassing NSObject in the first place?) then equality will work over there as well.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Custom equates operator
 
 
Q