SuperTony SuperTony - 1 year ago 104
Swift Question

UITableView numberOfRowsInSection - showing complete/incomplete tasks

I'm fairly new to the world of Swift and iOS and I'm creating a to-do list application. I have detail view that shows a list name and its tasks. My goal is to show the tasks in two separate sections, one for incomplete task and another for completed tasks.

In numberOfRowsInSection, if I use:

return list.tasks.count

I get this:

enter image description here

In my numberOfSectionsInTableView method I return 2 and as you can see in the image I am returning the tasks to both sections. It's obvious to me why, but I can't figure out how to get this right.

In list.task.count "task" is a class that has a property "var isComplete: Bool = false" that I was hoping to use to separate the complete/incomplete tasks here. Thank you in advance.

Sam Sam
Answer Source

It might be better to have to different arrays. One for complete tasks and one for incomplete tasks, then you can check the section of the Table View to know how many rows to return.

In numberOfRows:

if section == 0 {
    return completedTasks.count
} else {
    return incompleteTasks.count

This will also let you check in the cellForRowAtIndexPath the section and you won't need to mess around with remembering where in the array your complete/incomplete tasks are up to:

if indexPath.section == 0 {
    cell.task = completedTasks[indexPath.row]
} else {
    cell.task = incompleteTask[indexPath.row]


To address this issue in the comments:

if let destination = segue.destinationViewController as? TaskDetailViewController {
    let selectedRow = tableViewTasks.indexPathForSelectedRow?.row { 
        // let incompleteTask = list.incompleteTask[selectedRow] 
        // let completeTask = list.completeTask[selectedRow] 
        // destination.task = list.tasks[selectedRow] 

You should be checking if the tableViewTasks.indexPathForSelectedRow exists, not if the row exists so change:

let selectedRow = tableViewTasks.indexPathForSelectedRow?.row {


if let selectedIndexPath = tableViewTasks.indexPathForSelectedRow {

then check the section to see which array you want and the row to see which index you want :

if selectedIndexPath.section == 0 {
    destination.task = list.completedTasks[selectedIndexPath.row]
} else {
    destination.task = list.incompleteTasks[selectedIndexPath.row]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download