如何使我的Objective-C类符合Swift的"Equatable"协议? [英] How can I make my Objective-C class conform to Swift's `Equatable` protocol?

查看:170
本文介绍了如何使我的Objective-C类符合Swift的"Equatable"协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Objective-C类(碰巧是一个按钮,但这并不重要),在我的(混合语言)项目的另一部分,我有一系列这些按钮,我想使用find()方法获取按钮的索引.像这样:

I have an Objective-C class (that happens to be a button, but that is not important), and at another part of my (mixed language) project, I have an array of these buttons and I'd like to get the index of a button using the find() method. Like so:

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

但是我得到了

类型'ImplicitlyUnwrappedOptional'不符合协议等价

Type 'ImplicitlyUnwrappedOptional' does not conform to protocol equatable

好的,让我们转到Objective-C并让ButtonThing实现<Equatable>.但它无法识别.

Okay, so lets go to Objective-C and have ButtonThing implement <Equatable>. But it doesn't recognize that.

那我该怎么办? 现在,我围绕它进行构建,将数组强制为NSArray并使用indexOfObject.但这是丑陋的.和令人沮丧.

So what am I to do? For now I'm building around it, forcing the array to be an NSArray and using indexOfObject. But this is ugly. And frustrating.

推荐答案

首先,在Swift中为您的类编写一个自定义的==运算符.

First, in Swift write a custom == operator function for your class.

第二个也是在Swift中编写的类扩展添加了Equatable协议一致性.

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

例如,也许:

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

extension YourClass: Equatable {}

现在您的类符合Equatable,这是Swift特有的.您无法在Objective-C端执行此操作,因为您无法为Objective-C编写自定义运算符.

And now your class conforms to Equatable, which is Swift specific. You can not do this on the Objective-C end because you can not write custom operators for Objective-C.

这篇关于如何使我的Objective-C类符合Swift的"Equatable"协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆