Swift协议中的可选方法和重载

3
有没有办法在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:"

问题出在哪里?


1
这里有一篇关于这个话题的好文章:The Ghost of Swift Bugs Future - user887210
谢谢您提供这个链接! - iOS User
1个回答

3

UITableViewController是一个类,而不是协议。在协议中,您可以声明由您的类需要实现的方法。协议扩展使您能够编写协议方法的默认实现,即使您的类“继承”了该协议,您也无需实现此方法,但是您可以更改默认实现。

如果您编写以下类似代码:

protocol ExampleProtocol {
    func greetings() -> String
}

extension ExampleProtocol {
    func greetings() -> String {
        return "Hello World"
    }
}

class Example : ExampleProtocol {

}

然后你可以在控制台上看到“Hello World”,但如果你在你的类中重新编写这个方法:
func greetings() -> String {
    return "Hello"
}

现在你只会看到 "Hello"。 您可以从您的类中删除此方法并删除协议扩展声明,然后您将看到错误:“类型Example未遵守协议ExampleProtocol”。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接