How can I make my Objective-C class compatible with Swift `Equatable`?

I have an Objective-C class (which is a button, but that doesn't matter) and in another part of my (mixed language) project I have an array of these buttons and I would like to get the index of the button using a method find()

. For example:

func doSomethingWithThisButtonIndex(index:Int)
{
    let buttons = [firstButton, secondButton, thirdButton]
    if index == find(buttons, firstButton)
    {
        // we've selected the first button
    }
}

      

but i get

ImplicitlyUnwrappedOptional type does not conform to protocol standard

Ok, so let's move on to Objective-C and implement ButtonThing <Equatable>

. But it doesn't recognize it.

So what should I do? So far I am building around it by forcing the array to be NSArray and using indexOfObject

. But this is ugly. And frustrating.

+3


source to share


2 answers


First, in Swift, introduce a custom function ==

for your class.

Second, also in Swift, write a class extension that adds protocol conformance Equatable

.

Perhaps for example:



func == (lhs: YourClass, rhs: YourClass) -> Bool {
    // whatever logic necessary to determine whether they are equal
    return lhs === rhs
}

extension YourClass: Equatable {}

      

And now your class conforms Equatable

, which is Swift spec. You cannot do this on the Objective-C end, because you cannot write custom statements for Objective-C.

+8


source


If your Objective C class is NSObject, implement isEqual:

- (BOOL)isEqual:(_Nullable id)other;

      



This worked for me for Array.index (from: myobject) and == comparisons. NSObject is already Equatable, so using Swift extension doesn't work.

0


source







All Articles