respondsToSelector 的 Swift 等价物是什么? [英] What is the Swift equivalent of respondsToSelector?

查看:34
本文介绍了respondsToSelector 的 Swift 等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在谷歌上搜索过,但无法找出与 respondsToSelector: 等效的 swift 是什么.

这是我唯一能找到的(Swift 替代 respondsToSelector:)但不是'在我的情况下不太相关,因为它检查委托的存在,我没有委托我只想检查在设备上运行时是否存在新的 API,如果不回退到以前的版本api.

解决方案

如前所述,在 Swift 中大多数时候你可以通过 ? 可选的 unwrapper 操作符实现你需要的东西.当且仅当对象存在(不是 nil)并且方法已实现时,这允许您调用对象上的方法.

如果你仍然需要 respondsToSelector:,它仍然是 NSObject 协议的一部分.

如果您在 Swift 中对 Obj-C 类型调用 respondsToSelector:,那么它的工作方式与您预期的相同.如果您在自己的 Swift 类上使用它,则需要确保您的类派生自 NSObject.

这是一个 Swift 类的示例,您可以检查它是否响应选择器:

类工作者:NSObject{函数工作(){}func吃(食物:AnyObject){}函数睡眠(小时:整数,分钟:整数){}}让工人 = 工人()let canWork = worker.respondsToSelector(Selector("work"))//truelet canEat = worker.respondsToSelector(Selector("eat:"))//truelet canSleep = worker.respondsToSelector(Selector("sleep:minutes:"))//truelet canQuit = worker.respondsToSelector(Selector("quit"))//false

不要遗漏参数名称,这一点很重要.在此示例中,Selector("sleep::") Selector("sleep:minutes:") 相同.p>

I've googled but not been able to find out what the swift equivalent to respondsToSelector: is.

This is the only thing I could find (Swift alternative to respondsToSelector:) but isn't too relevant in my case as its checking the existence of the delegate, I don't have a delegate I just want to check if a new API exists or not when running on the device and if not fall back to a previous version of the api.

解决方案

As mentioned, in Swift most of the time you can achieve what you need with the ? optional unwrapper operator. This allows you to call a method on an object if and only if the object exists (not nil) and the method is implemented.

In the case where you still need respondsToSelector:, it is still there as part of the NSObject protocol.

If you are calling respondsToSelector: on an Obj-C type in Swift, then it works the same as you would expect. If you are using it on your own Swift class, you will need to ensure your class derives from NSObject.

Here's an example of a Swift class that you can check if it responds to a selector:

class Worker : NSObject
{
    func work() { }
    func eat(food: AnyObject) { }
    func sleep(hours: Int, minutes: Int) { }
}

let worker = Worker()

let canWork = worker.respondsToSelector(Selector("work"))   // true
let canEat = worker.respondsToSelector(Selector("eat:"))    // true
let canSleep = worker.respondsToSelector(Selector("sleep:minutes:"))    // true
let canQuit = worker.respondsToSelector(Selector("quit"))   // false

It is important that you do not leave out the parameter names. In this example, Selector("sleep::") is not the same as Selector("sleep:minutes:").

这篇关于respondsToSelector 的 Swift 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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