Reputation: 16416
I am trying to cast a UITableViewCell into its subclass when calling on dequeueReusableCellWithIdentifier. This is how am I doing it now:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let dogs = DBManager.getAllDogs()
let dog = dogs[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(Constants.dogViewCellReuseIdentifier,
forIndexPath: indexPath) as! DogViewCell
cell.configureWithDog(dog)
return cell
}
However, this approach uses an ugly forced cast. So I came up with this approach instead which is more Swifty:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let dogs = DBManager.getAllDogs()
let dog = dogs[indexPath.row]
if let cell = tableView.dequeueReusableCellWithIdentifier(Constants.dogViewCellReuseIdentifier,
forIndexPath: indexPath) as? DogViewCell {
cell.configureWithDog(dog)
return cell
} else {
return tableView.dequeueReusableCellWithIdentifier(Constants.dogViewCellReuseIdentifier,
forIndexPath: indexPath)
}
}
This approach I don't like either because I'm writing a lot more code in order to avoid the use of '!' forced unwrap optional cast.
What would be the proper and Swifty elegant way of doing this?
Upvotes: 0
Views: 131
Reputation: 119242
Ask yourself this: would you rather crash during development, on the exact line that tells you where a problem is, or have some oddball behaviour where something looks a little weird but you've got no clear idea why.
In the situation in your question you're only going to crash if you've configured the cell or the storyboard incorrectly. This isn't something the user or a web service is going to screw up for you.
Use !, have some tests in place so you know you haven't screwed up the configuration. Crashes during development when you've screwed up are helpful.
Upvotes: 2