Swift 2:UITableViewDataSource协议扩展

man*_*eGE 5 uitableview ios swift2 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()
    }   
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我有一个协议ArrayContainer,仅仅具有typealias和包含该typealias类型的对象阵列
  • 我的协议扩展UITableViewDataSource当类与符合要使用ArrayController的协议.这只是将数组的项数作为行数返回.该cellForRowAtIndexPath方法没有很好地实现,但它不是问题.
  • 我有一个UIViewController叫子类MyViewController,它实现这两种协议.

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

swi*_*lor 5

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

//: 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()
    }   
}
Run Code Online (Sandbox Code Playgroud)