Ios Swift 2:UITableViewDataSource协议扩展
我一直在玩协议扩展,我有一个问题。也许我想达到的目标无法实现。我有一个游乐场:Ios Swift 2:UITableViewDataSource协议扩展,ios,uitableview,swift2,protocol-extension,Ios,Uitableview,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, UITableViewD
//: 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()
}
}
这就是我所拥有和想要的:
- 我有一个协议<代码>阵列容器 它只有一个typealias和一个包含此typealias类型的对象的数组
- 我有一个协议扩展名<代码>UITableViewDataSource 当类符合<代码>阵列控制器 协议这只是将数组的项数作为行数返回。
方法没有很好地实现,但这不是问题所在cellforrowatinexpath
- 我有一个<代码>UIViewController 子类调用<代码>MyViewController 它实现了两个协议
问题是编译器会抱怨,因为MyViewController不符合
UITableViewDataSource
,但据我所知,它应该包含在UITableViewDataSource扩展中。我是不是遗漏了什么?或者Objective-C协议无法扩展?我知道现在响应有点晚,您甚至可能没有寻找这个答案,但我刚刚遇到了这个确切的问题,需要一个现实世界的“解决方案”。您可以在类中实现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()
}
}
这个问题可能与我非常确定的问题有关,因为协议扩展无法通过Objective-C访问,并且
UITableViewDataSource
实现需要ObjC访问。是的,我认为这就是问题所在,但它在任何地方都有记录吗?Swift中的协议扩展目前不支持动态调度。@ManueGE我在下面添加了一个实际实现。如果您认为这对您有效,您介意将其标记为已接受的答案吗?我不确定问这个是否不礼貌,所以请让我知道。这不是我所期望的,但我认为这是目前唯一的选择。