swiftinheritance的协议方法覆盖

我希望这会工作:

protocol Foo : UITableViewDelegate{ } extension Foo{ func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("ROW:\(indexPath.row)") } } class MyVC : UITableViewController, Foo{ //... } 

没有运气,但方法并没有被调用。 我错过了什么,或者这是真的不可能?

此外,没有编译器警告/错误,该方法只是没有被调用,有些人可能会考虑一个错误。

我认为这是因为你从已经实现了UITableViewDelegateinheritance。

你可以很容易地testing这个:

 class MyVC: UITableViewController { func tableView(tableView tv: UITableView, didSelectRowAtIndexPath ip: NSIndexPath) {} } 

这将导致

 error: overriding declaration requires an 'override' keyword 

编译器假定该方法已经在直接inheritance链中实现了。 因此,您的协议默认方法将不会被选中。

话虽如此,下面的变体也不起作用。 在协议中添加@objc使我的swiftc段错误…:

 import UIKit protocol Foo : UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath: NSIndexPath) } extension Foo { func tableView(tableView: UITableView, didSelectRowAtIndexPath _: NSIndexPath) { print("abcXXX") } } class ViewController: UIViewController, UITableViewDataSource, Foo { override func loadView() { self.view = UITableView(frame: CGRect()) } var tableView : UITableView { return self.view as! UITableView } override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self self.tableView.dataSource = self self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell1") } func tableView(tableView: UITableView, numberOfRowsInSection _: Int) -> Int { return 3 } func tableView(tableView: UITableView, cellForRowAtIndexPath ip: NSIndexPath) -> UITableViewCell { let cell = tableView .dequeueReusableCellWithIdentifier("MyCell1", forIndexPath: ip) cell.textLabel?.text = "p[\(ip.row)]" return cell } } 

因此,我认为我的答案只有50%是正确的。 大概协议扩展只能在静态绑定上下文,其中不包括ObjC协议?

更新:这似乎是正确的答案: 使用UIKit的面向协议的编程 。 精华:

我们不能做的:提供Objective-C协议的默认实现。