Max Max - 3 months ago 27
Swift Question

No 'dequeueReusableCellWithIdentifier' candidates produce the expected contextual result type 'DynamicTableViewCell?'

Implementing a custom table view cell and getting the below error on dequeueReusableCellWithIdentifier, can any one please help.

code :

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

//static DynamicTableViewCell *cell = nil;
var cell : DynamicTableViewCell?

var token: dispatch_once_t = 0
dispatch_once(&token) { () -> Void in
cell = tableView.dequeueReusableCellWithIdentifier("cell")
}

self.setUpCell(cell!, indexPath: indexPath)

return self.calculateHeightForConfiguredSizingCell(cell!)

}

Answer

I'm not sure if your way of doing it is a stable enough solution, but the Objective-C code you pointed can be translated into Swift as:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    struct My {
        static var cell : DynamicTableViewCell?
        static var token: dispatch_once_t = 0
    }

    dispatch_once(&My.token) { () -> Void in
        My.cell = tableView.dequeueReusableCellWithIdentifier("cell") as? DynamicTableViewCell
    }

    self.setUpCell(My.cell!, indexPath: indexPath)

    return self.calculateHeightForConfiguredSizingCell(My.cell!)
}

The error message No 'dequeueReusableCellWithIdentifier' candidates produce the expected contextual result type 'DynamicTableViewCell?' is saying that the return type of dequeueReusableCellWithIdentifier is UITableViewCell? which cannot be assigned to a variable of type DynamicTableViewCell?. You just need an explicit cast to suppress this error.

But other than that, you need to make your local cell and token static.

And you should also know that Swift 3 has excluded dispatch_once from its Standard Library.