An elegant way to dequeue a UITableViewCell
public protocol CellProtocol: class {
static var identifier: String { get }
static var nib: UINib { get }
}
extension UITableViewCell: CellProtocol {
// make sure the identifier is set to Class name
public static var identifier: String {
return String(describing: self)
}
public static var nib: UINib {
return UINib(
nibName: identifier,
bundle: Bundle(for: self)
)
}
}
public extension UITableView {
func register<T: CellProtocol>(cell: T.Type) {
self.register(
cell.nib,
forCellReuseIdentifier: cell.identifier
)
}
func deque<T: CellProtocol>(cell: T.Type) -> T {
return self.dequeueReusableCell(
withIdentifier: cell.identifier
)! as! T
}
func deque<T: CellProtocol>(cell: T.Type, for indexPath: IndexPath) -> T {
return self.dequeueReusableCell(
withIdentifier: cell.identifier,
for: indexPath
) as! T
}
}