检查是否在Swift中实现了可选的协议方法? [英] Check if optional protocol method is implemented in Swift?

查看:895
本文介绍了检查是否在Swift中实现了可选的协议方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个快速协议:

@objc protocol SomeDelegate {

  optional func myFunction()

}

我是我的一个课程:

weak var delegate: SomeDelegate?

现在我想检查委托已实施 myFunction

在objective-c中,我可以这样做:

In objective-c I can do:

if ([delegate respondsToSelector:@selector(myFunction)]) { 
...
}

但这在Swift中不可用。

But this is not available in Swift.

编辑:这与以下内容不同:什么是respontsToSelector的快速等价物?我专注于不在类上的类协议。

This is different from: What is the swift equivalent of respondsToSelector? I focus on class protocols not on classes.

如何检查我的代表是否有一个可选的方法实现?

推荐答案

Per Swift编程语言:


通过在调用需求名称后写
a问号来检查可选需求的实现,
如someOptionalMethod?( someArgument)。可选属性
要求,以及返回值的可选方法要求,
将在访问或调用
时始终返回相应类型的可选值,以反映可选$的事实b $ b要求可能尚未实施。

You check for an implementation of an optional requirement by writing a question mark after the name of the requirement when it is called, such as someOptionalMethod?(someArgument). Optional property requirements, and optional method requirements that return a value, will always return an optional value of the appropriate type when they are accessed or called, to reflect the fact that the optional requirement may not have been implemented.

所以意图不是要检查方法是否已实施,而是你尝试无论如何都要调用它并获得可选的返回。

So the intention is not that you check whether the method is implemented, it's that you attempt to call it regardless and get an optional back.

这篇关于检查是否在Swift中实现了可选的协议方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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