如何解决通用函数不将关联类型视为可派生的?

时间:2016-01-13 12:57:24

标签: swift generics inheritance protocols

Here is the actual code,我想改进。

cell中,我想强制CellSelf.Cell的子类,我们知道这些子类派生自UIView,这意味着它本身就是一个类。

import UIKit

// Conforming types will have a function called `cell`
// which returns a subclass of `Cell`
protocol cell {
   typealias Cell: UIView
}

extension UICollectionView: cell {
   typealias Cell = UICollectionViewCell
}
extension UITableView: cell {
   typealias Cell = UITableViewCell
}

extension cell {
   // Error, because Self.Cell is not a protocol
   func cell<Cell: Self.Cell>() -> Cell! {
      // The real function shouldn't return 
      // an implicitly unwrapped optional
      // but getting this to compile will solve my problem.
      return nil
   }
}

1 个答案:

答案 0 :(得分:1)

由于您要确保返回的单元格是一致类型提供的类型的子类,因此将其添加到协议要求中而不是尝试为每种Cell类型返回视图更有意义在协议扩展中使用单一方法

// Written in Swift 5.2
protocol cell {
    associatedtype Cell: UIView
    func cell() -> Cell!
}

extension UICollectionView: cell {
    typealias Cell = UICollectionViewCell

    func cell() -> UICollectionViewCell! {
        UICollectionViewCell()
    }
}
extension UITableView: cell {
    typealias Cell = UITableViewCell

    func cell() -> UITableViewCell! {
        UITableViewCell()
    }
}

符合条件的类型可以自由返回它们想要的任何子类,并且cell()方法将返回一个继承自该类型指定的单元格类的UIView。但是请注意,扩展这些类可防止子类覆盖协议的方法并指定其自己的单元格。

这是一个旧线程,您现在可能已经知道了。希望无论如何都会有帮助。