有没有办法覆盖 Swift 协议(protocol)中的可选方法?
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:"
有什么问题?
最佳答案
UITableViewController 是一个类,而不是一个协议(protocol)。在协议(protocol)中,您可以声明您的类所需的方法。协议(protocol)扩展使您能够编写协议(protocol)方法的默认实现,然后即使您的类“继承”了该协议(protocol),您也不必实现该方法,但您可以更改默认实现。
如果你写这样的代码:
protocol ExampleProtocol {
func greetings() -> String
}
extension ExampleProtocol {
func greetings() -> String {
return "Hello World"
}
}
class Example : ExampleProtocol {
}
然后您可以在您的控制台上看到“Hello World”,但是如果您在您的类中重写此方法:
func greetings() -> String {
return "Hello"
}
现在你只会看到“你好”。 您可以从您的类中删除此方法并删除协议(protocol)扩展声明,然后您将看到错误:“Type Example thas not conform to protocol ExampleProtocol”。
关于ios - Swift 协议(protocol)中的可选方法和重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36676678/