Skip to content

Instantly share code, notes, and snippets.

@tLewisII
Created September 29, 2016 21:04
Show Gist options
  • Save tLewisII/6717d280bed890243cc73d45b8149b6f to your computer and use it in GitHub Desktop.
Save tLewisII/6717d280bed890243cc73d45b8149b6f to your computer and use it in GitHub Desktop.
Safe dequeuing of collection and table view cells
protocol CellWithIdentifier:class {
associatedtype T = Self
static var resuseIdentifier: String { get }
}
extension UICollectionViewCell:CellWithIdentifier { }
extension UITableViewCell:CellWithIdentifier { }
extension CellWithIdentifier {
static var resuseIdentifier: String { return String(self) }
}
extension UICollectionView {
func deque<T: CellWithIdentifier where T.T == UICollectionViewCell>(cell type: T.Type, at indexPath: NSIndexPath) -> T {
return dequeueReusableCellWithReuseIdentifier(type.resuseIdentifier, forIndexPath: indexPath) as! T
}
}
extension UITableView {
func deque<T: CellWithIdentifier where T.T == UITableViewCell>(cell type: T.Type, at indexPath: NSIndexPath) -> T {
return dequeueReusableCellWithIdentifier(type.resuseIdentifier, forIndexPath: indexPath) as! T
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.deque(cell: NSObject.self, at: indexPath) // Compiler error
let cell = collectionView.deque(cell: UICollectionViewCell.self, at: indexPath) // Good
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment