[英]Argument type does not conform to expected type
我想要一個通用的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 VT does not conform to expected type 'Equatable'
錯誤與Argument of type VT does not conform to expected type 'Equatable'
。 因此,我明確添加了以下代碼: class OnboardingContentViewController<T: Codable & Equatable>: UIViewController, ItemDisplaying
這樣我可以顯示在ViewController中以T
傳遞的項目的類型是Codable & Equatable
。
我陷入了自己想要達到的目標,我想擁有一個數據源,該數據源至少包含可Codable & Equatable
的項目數組,並且我想為一種類型的要傳遞的UIViewController
。如何最好地做到這一點?
我沒有注意到associatedtype
不能引用其他協議,而必須引用具體的類型。 因此,以下工作原理:
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.