Objective-C 中的 protocol 里存在 @optional 关键字,被这个关键字修饰的方法并非必须要被实现。我们可以通过协议定义一系列方法,然后由实现协议的类选择性地实现其中几个方法。最好的例子我想应该是 UITableViewDataSource 和 UITableViewDelegate。前者中有两个必要方法
-tableView:numberOfRowsInSection:
-tableView:cellForRowAtIndexPath:
复制代码
原生的 Swift protocol 里没有可选项,所有定义的方法都是必须实现的
protocol MyProtocol {
func mustProtocolMethod() //必须实现方法
func mustProtocolMethod1() //必须实现方法
}
class MyClass: MyProtocol {
func mustProtocolMethod() {
print(“MyClass–>必须实现方法:mustProtocolMethod”)
}
func mustProtocolMethod1() {
print("MyClass-->必须实现方法:mustProtocolMethod1")
}
}
复制代码
如果我们想要像 Objective-C 里那样定义可选的协议方法,就需要将协议本身和可选方法都定义为Objective-C 的,也即在 protocol 定义之前以及协议方法之前加上 @objc。另外和 Objective-C 中的 @optional 不同,我们使用没有 @ 符号的关键字 optional 来定义可选方法
@objc protocol MyProtocol1 {
@objc optional func optionalProtocolMethod() //可选方法
func mustProtocolMethod1() //必须实现方法
}
class MyClass1: MyProtocol1 {
func mustProtocolMethod1() {
print(“MyClass1–>必须实现方法:mustProtocolMethod1”)
}
}
let cls1 = MyClass1()
cls1.mustProtocolMethod1()
复制代码
一个不可避免的限制是,使用 @objc 修饰的 protocol 就只能被 class 实现了,也就是说,对于 struct 和 enum 类型,我们是无法令它们所实现的协议中含有可选方法或者属性的
在 Swift 2.0 中,我们有了另一种选择,那就是使用 protocol extension。我们可以在声明一个 protocol 之后再用 extension 的方式给出部分方法默认的实现。这样这些方法在实际的类中就是可选实现的了