【发布时间】:2021-09-29 07:05:25
【问题描述】:
我已经开始创建一个基础存储库类,它将保存每个数据模型的数据,但我也希望它尽可能通用。 我还需要协议来通知这个存储库的消费者关于 in 的变化。想法是也有通用的数据更改机制,而不是根据数据类型定义 20 个协议。代码如下所示:
protocol BaseRepositoryDelegate {
associatedtype dataType
func didUpdateData(allData: [dataType], currentPage: [dataType], totalDataCount: Int, tag: Int?)
func didGetError(error: ApiError)
}
class BaseRepository<T> {
typealias dataType = T
var delegate: BaseRepositoryDelegate?
var tag: Int?
private(set) public var data = [T]()
private(set) public var currentPage = 0
private(set) public var totalCount = 0
init(delegate: BaseRepositoryDelegate, tag: Int? = nil) {
self.delegate = delegate
self.tag = tag
}
}
我遇到的问题是 delegate 属性会导致错误提示 Protocol 'BaseRepositoryDelegate' can only be used as a generic constraint because it has Self or associated type requirements 并且我无法解决该问题并保留存储库类和基本协议的通用功能。关于如何解决这个问题的任何想法?
我的最终目标是拥有一个 SpecificRepository 类,它可以继承 BaseRepository 并以某种方式提供可以为 Protocol 和 BaseRepository 定义 dataType 的参数。
class SpecificRepository: BaseRepository<MySpecificType> {
typealias dataType = MySpecificType
// I can override methods here or properties based
// on my use-case, or I can add specific functionality.
}
【问题讨论】:
标签: ios swift repository-pattern