【问题标题】:Generic parameter 'T' could not be inferred Xcode 11 iOS 13无法推断通用参数“T” Xcode 11 iOS 13
【发布时间】:2023-04-09 13:50:02
【问题描述】:

更新到 Xcode 11 后,我收到以下代码的“无法推断通用参数 'T'”。之前它可以正常工作。

extension UICollectionView {
    func register<T>(_ anyClass : T.Type) where T:UICollectionViewCell {
        register(anyClass.self, forCellWithReuseIdentifier: String.stringFromClass(anyClass))
    }

    func registerCells<T>(_ cells: [T.Type]) where T:UICollectionViewCell{
        for cellClass in cells{
            self.register(cellClass)
        }
    }
}

注册单元格时出错 -

collectionView.registerCells([CarouselSmallVideoCell.self, CarouselSmallArticleCell.self])

【问题讨论】:

    标签: ios swift xcode generics


    【解决方案1】:

    您不需要registerregisterCells 是通用的:

    func register(_ anyClass : UICollectionViewCell.Type) {
        print("\(anyClass.self)")
    }
    
    func registerCells(_ cells: [UICollectionViewCell.Type]) {
        for cellClass in cells{
            register(cellClass)
        }
    }
    

    【讨论】:

      【解决方案2】:

      T 需要从单一类型派生。我认为 Apple 在 XCode 11 中更多地执行了他们的编译器类型检查机制。

      阐述:

      编译器无法自信地推断出此处列出的类型:

      collectionView.registerCells([CarouselSmallVideoCell.self, CarouselSmallArticleCell.self])

      编译器必须检查T 的类型是CarouselSmallVideoCell 还是CarouselSmallArticleCell;它们不是同一类型。

      你可以做的就是改变你的函数签名:

      func registerCells&lt;T&gt;(_ cells: [T.Type]) where T:UICollectionViewCell

      收件人:

      func registerCells(_ cells: [UICollectionViewCell.Type])

      【讨论】:

        【解决方案3】:

        类型推断显然变得更笨了。先将数组放入变量中:

        let cells = [CarouselSmallVideoCell.self, CarouselSmallArticleCell.self]
        collectionView.registerCells(cells)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-19
          • 1970-01-01
          • 2015-09-22
          • 2021-11-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多