Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default equality operator for objects in Swift

Tags:

swift

When using find to search the index of an object in a array:

var index = find(Store.allItems, myItem)

The compiler says that the Item class does not conform to protocol Equatable.

My Item class is an object, so in my opinion, coming from C#, the default equality comparer should be reference equality.

In Swift, It seems that you need to specify Equatable on each reference-type in order for find to work.
Also, you need to imlement the == operator so that it uses === to compare references:

func ==(a:Item, b:Item) -> Bool {
    return a === b
}

Moreover, this last declaration must be top-level code, which disgust me...

I tried writing:

func ==(a:AnyObject, b:AnyObject) -> Bool {
    return a === b
}

but it seems not to work.

Is there some faster and more elegant way to achieve standard equality comparing for objects?

like image 294
Teejay Avatar asked Jun 30 '26 13:06

Teejay


1 Answers

Just try to make Item class conforming to Equatable:

extension Item:Equatable { }
func ==(lhs:Item, rhs:Item) -> Bool {
    return lhs === rhs
}
like image 138
rintaro Avatar answered Jul 03 '26 07:07

rintaro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!