Skip to content

Instantly share code, notes, and snippets.

@spookyd
Created April 30, 2019 22:30
Show Gist options
  • Select an option

  • Save spookyd/826a94395149a5b487972853eaf57434 to your computer and use it in GitHub Desktop.

Select an option

Save spookyd/826a94395149a5b487972853eaf57434 to your computer and use it in GitHub Desktop.
A convenience dequeue mechanism for collection and table views which eliminates casting
//
// UICellType+Extensions.swift
// Lucky 13
//
// Created by Luke Davis on 1/17/19.
// Copyright © 2019 Lucky 13. All rights reserved.
//
import Foundation
extension UICollectionView {
func dequeueReusableCell<T: UICollectionViewCell>(withReuseIdentifier identifier: String,
for indexPath: IndexPath) -> T {
let collectionCell = self.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
guard let cell = collectionCell as? T else {
fatalError("Unable to cast cell: [\(collectionCell)] to type: [\(T.self)]")
}
return cell
}
}
extension UITableView {
func dequeueReusableCell<T: UITableViewCell>(withIdentifier identifier: String) -> T {
let tableViewCell = self.dequeueReusableCell(withIdentifier: identifier)
guard let cell = tableViewCell as? T else {
fatalError("Unable to cast cell: [\(String(describing: tableViewCell))] to type: [\(T.self)]")
}
return cell
}
func dequeueReusableCell<T: UITableViewCell>(withIdentifier identifier: String, for indexPath: IndexPath) -> T {
let tableViewCell = self.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
guard let cell = tableViewCell as? T else {
fatalError("Unable to cast cell: [\(String(describing: tableViewCell))] to type: [\(T.self)]")
}
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment