Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading Operators in Swift

I'm trying to implement the Comparable protocol in Swift, but the compiler doesn't like any of my attempts to overload the < operator. I've checked the Apple documents and all the SO posts, but none of them even compile. Xcode gives me this warning:

Consecutive declarations on a line must be separated by ';'

and it keeps recommending me to insert a semicolon after the less than symbol. Any insight on what I'm doing wrong is appreciated.

class SomeClass: NSObject, Equatable, Comparable{

    var number: UInt32!

    override init()
    {
        super.init()
        self.number = arc4random()
    }

    func == (lhs: SomeClass, rhs: SomeClass) -> Bool
    {
        return true
    }

    func < (lhs: SomeClass, rhs: SomeClass) -> Bool
    {
        return true
    }

}
like image 763
WaltersGE1 Avatar asked Apr 08 '26 02:04

WaltersGE1


1 Answers

You see this error, because operators have to be overloaded outside the class definition, e.g. move

func == (lhs: SomeClass, rhs: SomeClass) -> Bool
{
    return true
}

func < (lhs: SomeClass, rhs: SomeClass) -> Bool
{
    return true
}

outside your class definition and it will work (except for that they do not return the proper result with this implementation).

like image 130
Sebastian Dressler Avatar answered Apr 09 '26 22:04

Sebastian Dressler