【发布时间】:2019-09-17 19:00:31
【问题描述】:
我想要一个通用的UIPageViewControllerDataSource,它可以基于两个通用参数来完成它的工作,如下所示:
protocol ItemDisplaying where Self: UIViewController {
associatedtype T
var item: T { get }
init(item: T)
}
final class LinearPageDataSource<V: ItemDisplaying> {
let items: [V.T]
init(items: [V.T]) {}
}
但是,数据源中的一个方法是这样的:
private func indexOf(_ viewController: V) -> Int {
return items.firstIndex(of: viewController.item) ?? NSNotFound
}
Argument of type V.T does not conform to expected type 'Equatable' 出错。
因此,我明确添加了这段代码:class OnboardingContentViewController<T: Codable & Equatable>: UIViewController, ItemDisplaying,这样我就可以显示在 ViewController 中以T 传入的项目的类型是Codable & Equatable。
我陷入了我想要实现的目标,我想要一个数据源,它包含一组至少为 Codable & Equatable 的项目,并且我想保留一个通用的可能性要传入的UIViewController 类型。我怎样才能最好地实现这一点?
【问题讨论】:
-
您不能将
Codable & Equatable约束应用于associatedtype吗?像这样:associatedtype T: Codable & Equatable。或者这不是您想要实现的目标? -
@MichaelFourre 这就是我想要做的,但它仍然给我同样的错误。
-