Skip to content

Instantly share code, notes, and snippets.

@ManWithBear
Created October 25, 2016 12:40
Show Gist options
  • Save ManWithBear/5d096812a1caf0a569beaceade2f8832 to your computer and use it in GitHub Desktop.
Save ManWithBear/5d096812a1caf0a569beaceade2f8832 to your computer and use it in GitHub Desktop.
Wrap common calls on tableview in generic way
protocol NibLoadable { }
extension NibLoadable where Self: UIView {
static var nibName: String {
return String(describing: self)
}
}
extension UITableViewCell: NibLoadable { }
protocol Reusable { }
extension Reusable where Self: UIView {
static var reuseIdentifier: String {
return String(describing: self)
}
}
extension UITableViewCell: Reusable { }
extension UITableView {
func register<T: UITableViewCell>(_ : T.Type) where T: Reusable, T: NibLoadable {
let nib = UINib(nibName: T.nibName, bundle: nil)
register(nib, forCellReuseIdentifier: T.reuseIdentifier)
}
func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T where T: Reusable {
guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)")
}
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment