什么是 Swift 等效的respondsToSelector?

编程入门 行业动态 更新时间:2024-10-22 15:30:15
本文介绍了什么是 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?

本文发布于:2023-11-12 20:28:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582458.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Swift   respondsToSelector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!