【问题标题】:Infer generic from any using protocol with associatedtype从任何使用关联类型的协议推断泛型
【发布时间】:2017-05-05 12:02:40
【问题描述】:

我正在尝试使这段代码工作

{ (tableview, originalItems, item, indexPath) in

    guard let matchingItem = originalItems.filter({ matching($0, 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

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

public protocol SectionRowRepresentable: Equatable {

  associatedtype Identity: Hashable

  var itemIdentifier: String { get }

}

【问题讨论】:

    标签: swift generics swift-protocols associated-types


    【解决方案1】:

    我最终是这样做的

      static func filter<T: SectionRowRepresentable>(_ items: [Any], match identifier: String) -> T? where T.Identity == AnyItemRepresentable.Identity {
    
        return items
          .flatMap { $0 as? T }
          .filter { $0.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
    
        }
    
      }
    

    【讨论】:

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