Objective-C 中的 protocol关键字

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 的方式给出部分方法默认的实现。这样这些方法在实际的类中就是可选实现的了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值