The goal is to dequeue cell like
let cell = CustomCollectionViewCell.dequeueReusable(collectionView, for: indexPath)
I'm trying like
class func dequeueReusable<T: UICollectionViewCell>(_ collectionView: UICollectionView, for indexPath: IndexPath) -> T {
return collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseID, for: indexPath) as! T
}
But it returns UICollectionViewCell, not CustomCollectionViewCell.
How to achieve this?
Your call to dequeueReusable
never requires any particular type for T
, so the most general is selected. The type you want, however, is Self
(the type of the current subclass).
The natural (but slightly wrong) way to write this would be:
class func dequeueReusable(_ collectionView: UICollectionView,
for indexPath: IndexPath) -> Self {
return collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseID,
for: indexPath) as! Self
}
I honestly don't know why this doesn't work. Self
can't be used in the as! Self
construct. It can, however, be tricked into working with a generic wrapper:
func cast<T>(_ value: Any) -> T { return value as! T }
With that, you get the working version:
class func dequeueReusable(_ collectionView: UICollectionView,
for indexPath: IndexPath) -> Self {
return cast(collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseID,
for: indexPath))
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments