Swift中如何实现返回UITableViewCell子类类型的泛型函数
实现方案
需求可以实现,核心问题是你原写法的泛型逻辑错误:泛型的类型参数由调用方在调用时决定,而非方法内部根据枚举分支动态决定,因此会出现类型不匹配的编译错误。正确实现如下:
1. 修改枚举定义
直接返回UITableViewCell父类类型即可,不需要泛型:
enum Color { case red, blue func cellType() -> UITableViewCell.Type { switch self { case .red: return RedCell.self case .blue: return BlueCell.self } } }
2. 给UITableView扩展新增非泛型重载方法
保留原有泛型方法不影响旧逻辑,新增一个接收父类类型的重载方法,匹配枚举返回的类型:
extension UITableView { // 原有泛型方法保留,兼容旧代码 func dequeueReusableCell<T: UITableViewCell>(_ type: T.Type, for indexPath: IndexPath) -> T { let identifier = String(describing: T.self) // 必须和Storyboard上设置的Cell标识一致 return dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! T } // 新增非泛型重载,适配枚举返回的类型 func dequeueReusableCell(_ type: UITableViewCell.Type, for indexPath: IndexPath) -> UITableViewCell { let identifier = String(describing: type) return dequeueReusableCell(withIdentifier: identifier, for: indexPath) } }
调用效果
完全符合你期望的写法,返回值为UITableViewCell类型:
let color = Color.red let cell = tableView.dequeueReusableCell(color.cellType(), for: indexPath)
如果后续需要做差异化配置,直接做类型转换即可:
switch cell { case let redCell as RedCell: // 配置RedCell case let blueCell as BlueCell: // 配置BlueCell default: break }
内容的提问来源于stack exchange,提问作者pkamb
相关产品推荐
相关产品推荐

