0

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?

1 Answer 1

3

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()
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

No, this form returns an optional. It is the original data source method, the newer, more commonly used method creates the cell if required, but that form accepts an index path and does not return an optional. In the question they have made it easier by using the older form so you don't need to worry about cell creation.
What if we had to take the IndexPath into consideration? Would the value of the dictionary be another nested dictionary with the row/section as the key?
How would you use the indexPath?
shouldn't you use array.removeFirst to get from the head since this is called "deQueue"?
In this case you don't need strict queue semantics. It is just a reuse pool (even though the method is called dequeue). It is more efficient to remove the last element of an array than to remove the first and have to shuffle all of the remaining indices (removeFirst is O(n) where n is the size of the array vs O(1) for popLast). The contract simply requires that you return an available cell, if possible, not the least recently used cell.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.