Skip to content

Instantly share code, notes, and snippets.

@ateliercw
Last active February 18, 2016 22:04
Show Gist options
  • Save ateliercw/9e2ecc43377ff6cf0cb6 to your computer and use it in GitHub Desktop.
Save ateliercw/9e2ecc43377ff6cf0cb6 to your computer and use it in GitHub Desktop.
Rough example of improving table view cell registration and dequeuing via generics
protocol AutomaticDequeue {
}
extension AutomaticDequeue where Self: AnyObject {
static var reuseIdentifer: String {
return NSStringFromClass(self) as String
}
}
extension UITableView {
func registerCellClass<CellClass: UITableViewCell where CellClass: AutomaticDequeue>(cellClass: CellClass.Type) {
registerClass(cellClass, forCellReuseIdentifier: cellClass.reuseIdentifer)
}
func registerHeaderFooterClass<HeaderFooterClass: UITableViewHeaderFooterView where HeaderFooterClass: AutomaticDequeue>(headerFooterClass: HeaderFooterClass.Type) {
registerClass(headerFooterClass, forHeaderFooterViewReuseIdentifier: headerFooterClass.reuseIdentifer)
}
func cellForIndexPath<CellClass: UITableViewCell where CellClass: AutomaticDequeue>(indexPath: NSIndexPath) -> CellClass {
guard let cell = dequeueReusableCellWithIdentifier(CellClass.reuseIdentifer, forIndexPath: indexPath) as? CellClass else {
fatalError("Could not dequeue cell with identifier \(CellClass.reuseIdentifer)")
}
return cell
}
func headerForIndexPath<HeaderFooterClass: UITableViewHeaderFooterView where HeaderFooterClass: AutomaticDequeue>(indexPath: NSIndexPath) -> HeaderFooterClass {
guard let header = dequeueReusableHeaderFooterViewWithIdentifier(HeaderFooterClass.reuseIdentifer) as? HeaderFooterClass else {
fatalError("Could not dequeue header with identifier \(HeaderFooterClass.reuseIdentifer)")
}
return header
}
func footerForIndexPath<HeaderFooterClass: UITableViewHeaderFooterView where HeaderFooterClass: AutomaticDequeue>(indexPath: NSIndexPath) -> HeaderFooterClass {
guard let footer = dequeueReusableHeaderFooterViewWithIdentifier(HeaderFooterClass.reuseIdentifer) as? HeaderFooterClass else {
fatalError("Could not dequeue footer with identifier \(HeaderFooterClass.reuseIdentifer)")
}
return footer
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment