Last active
March 11, 2019 19:18
-
-
Save wjlafrance/8f5278fd04313099254f6a19bcb595bb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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