我一直在玩协议扩展,我有一个问题。也许我想达到的目标是做不到的。我有一个操场:
//: 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()
}
}这就是我所拥有的和我想要的:
ArrayContainer,它只有一个类型别名和一个数组,其中包含这个类型的对象。UITableViewDataSourceArrayController协议时,可以使用的协议扩展。这只是将数组的项目数作为行数返回。cellForRowAtIndexPath方法没有很好的实现,但它不是问题所在。UIViewControllerMyViewController的子类,它实现了这两个协议。问题是编译器抱怨是因为MyViewController不符合UITableViewDataSource,但据我所知,UITableViewDataSource扩展应该涵盖它。我是不是漏掉了什么?或者目标-C协议不能扩展?
发布于 2016-05-26 17:14:20
我知道现在回应有点晚了,你甚至可能并不是在寻找这个答案,但我只是偶然发现了这个问题,需要一个现实世界的“解决方案”。您可以在类中实现UITableViewDataSource方法,然后立即将工作交给协议扩展,如下例所示。如果斯威夫特进行了不再需要这种改进的改进,那么很容易将代码更改回原来的文章中。
//: 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()
}
}https://stackoverflow.com/questions/32582638
复制相似问题