swift里可以替协议默认实现,即A类定义了一个协议,然后为protocol 写一个extension,在extension里为协议提供一个默认的实现方法,B类只需遵守次协议,B类不需写任何实现方法,只需调用就可。
如 student 类提供了一个协议借口:
protocol ScoresDelegate: class {
func allScores()
}
class Student: NSObject {
weak var delegate: ScoresDelegate?
}
extension ScoresDelegate {
func allScores() {
print("all scores")
}
}
B类只需遵守此协议,不用实现协议方法也可以通过。用的时候直接调用即可
class ViewController: UIViewController, ScoresDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.allScores()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
此时,打印结果为 all scores
当然,你也可以重新实现改协议方法:
class ViewController: UIViewController, ScoresDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.allScores()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func allScores() {
print("重新实现")
}
}
此时,打印结果为 重新实现
为协议扩张在某些时候可以为默认省去大量重复的代码。比如遵守该协议代理的类都只进行同一个步骤,我们不必在每个遵守该协议的类中重写操作;也不用去在别处封装一个方法,然后在遵守的类中调用。只需在protocol extension实现操作即可。
当然,你们可能注意到了我的协议后面跟了个class。这是因为,对于delegate,我们会在声明代理属性时将它指定为weak,在这个delegate实际对象被调用的时候,会被置为nil。但是swift里面,protocol可以被class以外的其它类型遵守,比如struct,但是struct是值类型,不存在引用计数来管理内存。而weak只使用类,所以在class类里若想使用weak delegate解决循环引用,需要在协议后面加class