Ios 带自投射的Swift通用扩展
目标是像cell一样退出队列Ios 带自投射的Swift通用扩展,ios,swift,generics,Ios,Swift,Generics,目标是像cell一样退出队列 let cell = CustomCollectionViewCell.dequeueReusable(collectionView, for: indexPath) 我正在努力 class func dequeueReusable<T: UICollectionViewCell>(_ collectionView: UICollectionView, for indexPath: IndexPath) -> T { return co
let cell = CustomCollectionViewCell.dequeueReusable(collectionView, for: indexPath)
我正在努力
class func dequeueReusable<T: UICollectionViewCell>(_ collectionView: UICollectionView, for indexPath: IndexPath) -> T {
return collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseID, for: indexPath) as! T
}
class func-dequeuereusables(collectionView:UICollectionView,对于indexPath:indexPath)->T{
将collectionView.dequeueReusableCell(带ReuseIdentifier:self.reuseID,for:indexPath)返回为!T
}
但它返回UICollectionViewCell,而不是CustomCollectionViewCell
如何实现这一点?您对
dequeue
的调用从不需要T
的任何特定类型,因此选择了最通用的类型。但是,您想要的类型是Self
(当前子类的类型)
写这篇文章的自然(但有点错误)方式是:
class func dequeueReusable(_ collectionView: UICollectionView,
for indexPath: IndexPath) -> Self {
return collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseID,
for: indexPath) as! Self
}
我真的不知道为什么这样不行Self
不能在as中使用!自我构建。但是,它可能会被诱骗使用通用包装器:
func cast<T>(_ value: Any) -> T { return value as! T }
self.reuseID
无法在类中编译,因此您应该将您的问题包含在函数形式的实际代码中。顺便说一句,将此方法定义为UICollectionView
上的扩展,并将UICollectionViewCell
子类类型作为通用输入参数传递会更有意义。建议查看。它做你想做的事。(如果我没有误解你的问题的话)具有关联类型的协议扩展可能是更好的选择,@vadian:像这样?:)@MartinR是的,像这样的unsafeDowncast(…,to:self)
将是另一种选择:。谢谢;我知道我在什么地方见过别的解决办法。事实上,这比斯威夫特更好。我认为这应该愚弄那一个。
class func dequeueReusable(_ collectionView: UICollectionView,
for indexPath: IndexPath) -> Self {
return cast(collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseID,
for: indexPath))
}