yesthisisjoe yesthisisjoe - 4 months ago 9
iOS Question

Better way to initialize different cell types inside an if statement

In my code, a

cell
will be of one type if it is in the first
tableView
section, and another if it is not.

var cell = UITableViewCell()

if indexPath.section == 0 {
cell = tableView.dequeueReusableCellWithIdentifier("UpcomingWorkoutCell", forIndexPath: indexPath) as! MyWorkoutsTableViewCell
cell.nameLabel.text = workout.trainer.name
cell.dateLabel.text = workout.getDateString()
cell.timeLabel.text = workout.getTimeString()
cell.trainerImage.image = workout.image
} else {
cell = tableView.dequeueReusableCellWithIdentifier("PastWorkoutCell", forIndexPath: indexPath) as! PastWorkoutTableViewCell
cell.nameLabel.text = workout.trainer.name
cell.dateLabel.text = workout.getDateString()
cell.timeLabel.text = workout.getTimeString()
cell.trainerImage.image = workout.image
cell.ratingControl.rating = workout.rating // Exclusive to PastWorkoutCell
}


Is there a better way to write this? Can I somehow get rid of the initial declaration as a
UITableViewCell
and shorten my code by a line?

Also, MyWorkoutsTableViewCell and PastWorkoutCell have almost all their properties in common. Can I avoid repeating code in each of the branches of the if statement to set all of them? Right now cell is a
UITableViewCell
that doesn't have any properties so I can't seem to do it outside the two branches.

Answer

Have you try this

var cell = tableView.dequeueReusableCellWithIdentifier("UpcomingWorkoutCell", forIndexPath: indexPath) as! MyWorkoutsTableViewCell
if indexPath.section != 0 {
    cell = tableView.dequeueReusableCellWithIdentifier("PastWorkoutCell", forIndexPath: indexPath) as! PastWorkoutTableViewCell
    cell.ratingControl.rating = workout.rating
}
cell.nameLabel.text = workout.trainer.name
cell.dateLabel.text = workout.getDateString()
cell.timeLabel.text = workout.getTimeString()
cell.trainerImage.image = workout.image