Skip to content

Instantly share code, notes, and snippets.

@wjlafrance
Last active March 11, 2019 19:18
Show Gist options
  • Save wjlafrance/8f5278fd04313099254f6a19bcb595bb to your computer and use it in GitHub Desktop.
Save wjlafrance/8f5278fd04313099254f6a19bcb595bb to your computer and use it in GitHub Desktop.
import UIKit
protocol IdentifierDequeueableCell where Self: UITableViewCell {
static var dequeueIdentifier: String { get }
}
extension IdentifierDequeueableCell {
static var dequeueIdentifier: String {
return String(describing: self)
}
}
extension UITableView {
func dequeueReusableCell<T: IdentifierDequeueableCell>(withType: T.Type, for indexPath: IndexPath) -> T {
let cell = dequeueReusableCell(withIdentifier: T.dequeueIdentifier, for: indexPath)
guard let typedCell = cell as? T else {
preconditionFailure("Cell is not correct type")
}
return typedCell
}
}
// Normally
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MyCellSubclass", for: indexPath) as? MyCellSubclass else {
preconditionFailure("dequeue gave back nil or wrong cell type!")
}
return cell
// With extension
return tableView.dequeueReusableCell(withType: MyCellSubclass.type, for: indexPath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment