Created
September 29, 2016 21:04
-
-
Save tLewisII/6717d280bed890243cc73d45b8149b6f to your computer and use it in GitHub Desktop.
Safe dequeuing of collection and table view cells
This file contains 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
protocol CellWithIdentifier:class { | |
associatedtype T = Self | |
static var resuseIdentifier: String { get } | |
} | |
extension UICollectionViewCell:CellWithIdentifier { } | |
extension UITableViewCell:CellWithIdentifier { } | |
extension CellWithIdentifier { | |
static var resuseIdentifier: String { return String(self) } | |
} | |
extension UICollectionView { | |
func deque<T: CellWithIdentifier where T.T == UICollectionViewCell>(cell type: T.Type, at indexPath: NSIndexPath) -> T { | |
return dequeueReusableCellWithReuseIdentifier(type.resuseIdentifier, forIndexPath: indexPath) as! T | |
} | |
} | |
extension UITableView { | |
func deque<T: CellWithIdentifier where T.T == UITableViewCell>(cell type: T.Type, at indexPath: NSIndexPath) -> T { | |
return dequeueReusableCellWithIdentifier(type.resuseIdentifier, forIndexPath: indexPath) as! T | |
} | |
} | |
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { | |
let cell = collectionView.deque(cell: NSObject.self, at: indexPath) // Compiler error | |
let cell = collectionView.deque(cell: UICollectionViewCell.self, at: indexPath) // Good | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment