[英]Argument type does not conform to expected type
I want a generic UIPageViewControllerDataSource
that can do its thing based on two generic parameters, like so: 我想要一个通用的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]) {}
}
However, a method within the data source like this: 但是,数据源中的方法如下:
private func indexOf(_ viewController: V) -> Int {
return items.firstIndex(of: viewController.item) ?? NSNotFound
}
Errors out with Argument of type VT does not conform to expected type 'Equatable'
. Argument of type VT does not conform to expected type 'Equatable'
错误与Argument of type VT does not conform to expected type 'Equatable'
。 Therefore, I added explicitly this code: class OnboardingContentViewController<T: Codable & Equatable>: UIViewController, ItemDisplaying
so I can show that the type of the item passed in as T
in the ViewController is Codable & Equatable
. 因此,我明确添加了以下代码: class OnboardingContentViewController<T: Codable & Equatable>: UIViewController, ItemDisplaying
这样我可以显示在ViewController中以T
传递的项目的类型是Codable & Equatable
。
I'm getting stuck in what I'm trying to achieve, I'd like to have a data source that takes an array of items that are at least Codable & Equatable
and I'd like to keep a generic possibility for a type of UIViewController
to be passed in. How can I best achieve this? 我陷入了自己想要达到的目标,我想拥有一个数据源,该数据源至少包含可Codable & Equatable
的项目数组,并且我想为一种类型的要传递的UIViewController
。如何最好地做到这一点?
I didn't notice that an associatedtype
can't refer to another protocol, but has to refer to a concrete type. 我没有注意到associatedtype
不能引用其他协议,而必须引用具体的类型。 Therefore the following works: 因此,以下工作原理:
protocol ItemDisplaying where Self: UIViewController {
associatedtype T: Decodable & Equatable
var item: T { get }
init(item: T)
}
final class LinearPageDataSource<V: ItemDisplaying>: NSObject, UIPageViewControllerDataSource {
let items: [V.T]
init(items: [V.T]) {
self.items = items
}
func contentViewController(atIndex index: Int) -> V? {
return V.init(item: items[index])
}
final class OnboardingContentViewController: UIViewController, ItemDisplaying {
typealias T = OnboardingItem // this is a struct, conforming to Decodable and Equatable
let item: T
required init(item: T) {
self.item = item
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.