如何在Swift协议中定义可选方法? [英] How to define optional methods in Swift protocol?

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

问题描述

Swift有可能吗?如果没有,那么有没有办法解决?

Is it possible in Swift? If not then is there a workaround to do it?

推荐答案

如果你想使用可选方法,你必须使用 @objc 标记您的协议属性:

If you want to use optional methods, you must mark your protocol with @objc attribute:

@objc protocol MyProtocol {

    @objc optional func doSomething()

}

class MyClass : MyProtocol {

    // no error

}

否则,Swift协议就像其他OO上的接口一样语言,必须实现接口中定义的所有方法。

Otherwise, Swift protocols behave like interfaces on other OO languages, where all methods defined in interfaces must be implemented.

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

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