Swift2:UITableViewDataSource协议扩展

Swift 2: UITableViewDataSource protocol extension

我一直在研究协议扩展,但遇到了问题。也许我想达到的目标无法完成。我有这个游乐场:

//: Playground - noun: a place where people can play

import UIKit

protocol ArrayContainer {
    typealias T
    var array: [T] { get }
}

class MyViewController: UIViewController, ArrayContainer, UITableViewDataSource {
    typealias T = String
    var array = ["I am", "an Array"] 
}

extension UITableViewDataSource where Self: ArrayContainer {

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // Whatever
        return UITableViewCell()
    }   
}

这就是我所拥有的和我想要的:

问题是编译器抱怨,因为 MyViewController 不符合 UITableViewDataSource,但据我所知,它应该被 UITableViewDataSource 扩展覆盖。我在这里错过了什么吗?或者 Objective-C 协议无法扩展?

我知道现在回复有点晚,您甚至可能不会寻找这个答案,但我刚遇到这个确切的问题并且需要一个真实的世界 "solution"。您可以在 class 中实现 UITableViewDataSource 方法,然后立即将工作交给协议扩展,如下例所示。如果 swift 进行了不再需要此的改进,则很容易改回原始 post 中的代码。

//: Playground - noun: a place where people can play

import UIKit

protocol ArrayContainer {
    associatedtype T
    var array: [T] { get }
}

class MyViewController: UIViewController, ArrayContainer, UITableViewDataSource {
    typealias T = String
    var array = ["I am", "an Array"]

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.internal_numberOfSectionsInTableView(tableView)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.internal_tableView(tableView, numberOfRowsInSection: section)
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return self.internal_tableView(tableView, cellForRowAtIndexPath: indexPath)
    }
}

extension UITableViewDataSource where Self: ArrayContainer {

    func internal_numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func internal_tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }

    func internal_tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // Whatever
        return UITableViewCell()
    }   
}