【问题标题】:Argument type does not conform to expected type参数类型不符合预期类型
【发布时间】: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&lt;T: Codable &amp; Equatable&gt;: UIViewController, ItemDisplaying,这样我就可以显示在 ViewController 中以T 传入的项目的类型是Codable &amp; Equatable

我陷入了我想要实现的目标,我想要一个数据源,它包含一组至少为 Codable &amp; Equatable 的项目,并且我想保留一个通用的可能性要传入的UIViewController 类型。我怎样才能最好地实现这一点?

【问题讨论】:

  • 您不能将Codable &amp; Equatable 约束应用于associatedtype 吗?像这样:associatedtype T: Codable &amp; Equatable。或者这不是您想要实现的目标?
  • @MichaelFourre 这就是我想要做的,但它仍然给我同样的错误。

标签: ios swift generics


【解决方案1】:

我没有注意到 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
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多