ios - Swift 协议(protocol)中的可选方法和重载

标签 ios swift cocoa protocols

有没有办法覆盖 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/

相关文章:

html - @font-face 在 iOS 上不起作用?只是有些字体不起作用?

swift - 为什么我的 View 的背景颜色没有快速改变?

swift - 百分比概率算法

cocoa - 如何在 NSObject 子类上简洁地迭代 @properties 以从 plist 设置属性?

objective-c - 为什么释放后要设置为nil?

cocoa - 如何知道文件是否为 "stored in the file-system caches"

ios - 我应该在执行后将 block 引用设置为 nil 吗?

ios - 在 ABPeoplePickerNavigationController 中添加滑动删除功能

ios - 访问 swift 中该函数外部的 override func viewDidLoad() { super.viewDidLoad() 函数中创建的变量

swift - 为什么不建议将 UIImage 数据保存到 UserDefaults?