从任何具有关联类型的使用协议推断泛型

Infer generic from any using protocol with associatedtype

我正在尝试使此代码正常工作

{ (tableview, originalItems, item, indexPath) in

    guard let matchingItem = originalItems.filter({ matching([=10=], with: item.itemIdentifier) }).first else {

        LogManager.Fatal.log("No item matching identifier : \(item.itemIdentifier)")

        return nil

    }
Some code
}

originalItems[Any] 而我的函数是

static func matching<T: SectionRowRepresentable>(_ item: T, with identifier: String) -> Bool where T.Identity == AnyItemRepresentable.Identity

我如何从 Any 推断 T 知道 SectionRowRepresentable 有一个关联类型 Identity

public protocol SectionRowRepresentable: Equatable {

  associatedtype Identity: Hashable

  var itemIdentifier: String { get }

}

我最后这样做了

  static func filter<T: SectionRowRepresentable>(_ items: [Any], match identifier: String) -> T? where T.Identity == AnyItemRepresentable.Identity {

    return items
      .flatMap { [=10=] as? T }
      .filter { [=10=].identity == identifier }
      .first

  }

  static func tableviewCellFactory() -> TableViewCellFactoryBlock {

    return { (tableview, originalItems, item, indexPath) in

      if let movieItem = filter(originalItems, match: item.itemIdentifier) as MovieItem? {

        let adapter = TitleLabelViewAdapter(mapping: movieItem.identifier, title: movieItem.title)
        let factory = TableViewCellFactory<TitleLabelView>(identifier: movieItem.identifier,
                                                           reuseIdentifier: TitleLabelView.ReuseIdentifier,
                                                           adapter: adapter)

        return AnyTableViewCellFactory(factory)

      } else if let adItem = filter(originalItems, match: item.itemIdentifier) as NativeAdItem? {

        let reuseIdentifier = "\(TopImageBottomTitleLabelView.ReuseIdentifier) \(adItem.identifier)"
        let adapter = TopImageBottomTitleLabelViewAdapter(mapping: adItem.identifier, title: adItem.title)
        let factory = TableViewCellFactory<TopImageBottomTitleLabelView>(identifier: adItem.identifier,
                                                                         reuseIdentifier: reuseIdentifier,
                                                                         adapter: adapter)

        return AnyTableViewCellFactory(factory)

      }

      LogManager.Fatal.log("No item matching identifier : \(item.itemIdentifier)")

      return nil

    }

  }