简体   繁体   English

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

[英]Optional methods in Swift protocol and overloading

Is there way to override optional methods in Swift protocol?有没有办法覆盖 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")
    }
}

Why in UIKit there is similar example?为什么在 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 statement is required!!!需要override语句!!! But UITableViewController does not respond to selector "tableView: estimatedHeightForRowAtIndexPath:"但是UITableViewController不响应选择器"tableView: estimatedHeightForRowAtIndexPath:"

What is problem?什么是问题?

UITableViewController is a class, not a protocol. UITableViewController 是一个类,而不是一个协议。 In protocol you can declare method that is required by your class.在协议中,您可以声明您的类所需的方法。 Protocol extensions give you ability to write default implementation of your protocol method and then even if your class "inherit" this protocol you don't have to implement this method but you can change the default implementation.协议扩展使您能够编写协议方法的默认实现,然后即使您的类“继承”此协议,您也不必实现此方法,但您可以更改默认实现。

If you write code something like this:如果你写这样的代码:

protocol ExampleProtocol {
    func greetings() -> String
}

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

class Example : ExampleProtocol {

}

then you can see "Hello World" on your console but if you re-write this method in your class:那么你可以在你的控制台上看到“Hello World”,但是如果你在你的类中重写这个方法:

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

now you will see just "Hello".现在你只会看到“你好”。 You can remove this method from your class and remove the protocol extension declaration and then you will see error: "Type Example thas not conform to protocol ExampleProtocol".您可以从您的类中删除此方法并删除协议扩展声明,然后您将看到错误:“类型示例不符合协议 ExampleProtocol”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM