Reputation: 131
My friend was asked to implement dequeueReusableCell(withIdentifier:) in swift for iOS Engineer role at Facebook.
Question
Imagine that you work an Apple, and suddenly the implementation code is lost. What you have to do is to implement the code for dequeueReusableCell(withIdentifier:). How would you implement that function?
class UItableView: UIScrollView {
func dequeueReusableCell(withIdentifier identifier: String) -> UITableViewCell? {
}
}
My Implementation:
class UItableView: UIScrollView {
let cells = [UITableViewCell]()
func dequeueReusableCell(withIdentifier identifier: String) -> UITableViewCell? {
return cells.filter { $0.identifier == identifier }.first
}
}
I am not sure how correct it is.
I think dictionary that store cells with there index would be a better approach.
Could anyone please comment how to write this function?
Upvotes: 0
Views: 452
Reputation: 114836
I would create a dictionary that associates the identifier
with an array of available cells. When you need a cell you remove and return the last element if possible.
If there are no cells available you return nil
The popLast()
function provides the functionality we need and it has O(1) complexity.
The tableview would need to add cells back onto the reuse array once they were no longer visible.
class UItableView: UIScrollView {
let cellReusePools: [String:[UITableviewCell]] = [:]
func dequeueReusableCell(withIdentifier identifier: String) -> UITableViewCell? {
return cellReusePools[identifier]?.popLast()
}
}
Upvotes: 3