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

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

问题描述

我已经用谷歌搜索过,但无法找到与 respondsToSelector: 等效的 swift 是什么.

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

解决方案

如前所述,在 Swift 大多数情况下,您可以使用 ? 可选的解包操作符来实现您所需要的强>.当且仅当对象存在(不是 nil)并且该方法已实现时,这允许您调用对象上的方法.

如果您仍然需要 respondsToSelector:,它仍然作为 NSObject 协议的一部分存在.

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

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

class Worker : NSObject{功能工作(){}功能吃(食物:AnyObject){}func 睡眠(小时:整数,分钟:整数){ }}让工人 = 工人()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:") 相同.>

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:").

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

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