1

我想做一个通用的 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

4

1 回答 1

1

我还希望 TableView 单元格是通用的

你根本不需要那个。您已经将该configure(with:)方法定义为通用方法。无需使类本身成为通用类。


鉴于上述陈述,如果您对此表示满意,那么您的实现将非常简单:

class ConfigureCell: UITableViewCell {
    func configure<Model: ConfigureModel>(with value: Model) {
        let description = value.modelDescription()

        print("ConfigureCell description: \(description)")
    }
}

class ObjectDataSource<T: ConfigureModel>: NSObject, UITableViewDataSource {
    var values: [T] = []

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = self.values[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "TagCell", for: indexPath) as! ConfigureCell
        cell.configure(with: item)
        return cell
    }
}
于 2019-04-18T09:50:27.243 回答