我想做一个通用的 TableView DataSource 类,它包含一个数组ConfigureModel
:
protocol ConfigureModel {
associatedtype ModelType
var name: String { get set }
var modelDescription: String { get }
}
我还希望 TableView 单元格是通用的:
class ConfigureCell<ConfigureType>: UITableViewCell, Configure {
func configure<Model: ConfigureModel>(with value: Model) where ConfigureType == Model.ModelType {
let description = value.modelDescription
print("ConfigureCell description: \(description)")
}
}
所以我ConfigureCell
采用了通用Configure
协议:
protocol Configure {
associatedtype ConfigureType
func configure<Model: ConfigureModel>(with value: Model) where Model.ModelType == ConfigureType
}
现在我可以让模型采用ConfigureModel
可以在ConfigureCell
类中使用的协议:
struct Tag {
....
}
extension Tag: ConfigureModel {
typealias ModelType = Tag
}
这工作正常。现在进行ObjectDataSource
通用:
class ObjectDataSource<T: ConfigureModel>: NSObject, UITableViewDataSource, UITableViewDelegate {
var values: [T] = []
....
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = self.values[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "TagCell", for: indexPath) as! ConfigureCell<T>
cell.configure(with: item)
在这里我有一个问题,我已经尝试了好几个小时才能解决。最后一条cell.configure(with: item
语句 Xcode 显示错误:Instance method 'configure(with:)' requires the types 'T' and 'T.T' be equivalent
我知道我必须在课堂上创建一个通用的 where 子句,但我很难找出应该是什么。
class ObjectDataSource<T: ConfigureModel>: NSObject, UITableViewDataSource, UITableViewDelegate
where T == ???? {
我制作了一个 Xcode Playground 可以工作,但是注释掉的部分不起作用。你可以在这里得到它:GenericDataSource Xcode PlayGround