Skip to content

Instantly share code, notes, and snippets.

@nahuelDeveloper
Created April 14, 2022 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nahuelDeveloper/7b2a67a66390941109517818fc1e64d8 to your computer and use it in GitHub Desktop.
Save nahuelDeveloper/7b2a67a66390941109517818fc1e64d8 to your computer and use it in GitHub Desktop.
Extension for easier registering and dequeueing of TableView cells
protocol ReusableView: AnyObject {
static var defaultReuseIdentifier: String { get }
}
extension ReusableView where Self: UIView {
static var defaultReuseIdentifier: String {
return String(describing: self)
}
}
extension UITableViewCell: ReusableView {
static var defaultReuseIdentifier: String {
return String(describing: self)
}
}
extension UITableView {
func register<T: UITableViewCell>(_: T.Type) {
register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier)
}
func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)")
}
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment