有没有办法覆盖Swift协议中的可选方法?
protocol Protocol {
func requiredMethod()
}
extension Protocol {
func optionalMethod() {
// do stuff
}
}
class A: Protocol {
func requiredMethod() {
print("implementation in A class")
}
}
class B: A {
func optionalMethod() { // <-- Why `override` statement is not required?
print("AAA")
}
}
为什么在UIKit中有类似的例子?
protocol UITableViewDelegate : NSObjectProtocol, UIScrollViewDelegate {
// ......
optional public func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
}
class MyTVC: UITableViewController {
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{}
需要 override
声明!但UITableViewController
不响应选择器"tableView: estimatedHeightForRowAtIndexPath:"
有什么问题?
答案 0 :(得分:2)
UITableViewController是一个类,而不是协议。在协议中,您可以声明类所需的方法。协议扩展使您能够编写协议方法的默认实现,然后即使您的类“继承”此协议,您也不必实现此方法,但您可以更改默认实现。
如果您编写类似这样的代码:
protocol ExampleProtocol {
func greetings() -> String
}
extension ExampleProtocol {
func greetings() -> String {
return "Hello World"
}
}
class Example : ExampleProtocol {
}
然后您可以在控制台上看到“Hello World”,但如果您在班级中重写此方法:
func greetings() -> String {
return "Hello"
}
现在你会看到“你好”。 您可以从类中删除此方法并删除协议扩展声明,然后您将看到错误:“类型示例不符合协议ExampleProtocol”。