-1

I'm building a todo app. I want the user to be able to create tasks as well as categories for the tasks. I'm having some problem trying to figure out how to display the right tasks in the tableview based on which category it belongs to. I also want the user to be able to choose a due date.

Lets say we have an array with the categories, var categories = ["Work", "Private"]

How would I store the task, the category for the task, and the due date? And then access the right task based on which category it belongs to.

if task has category "home" print task.

at first I thought about storing it in a dictionary var tasks = ["Category": "Task"] but then I couldn't figure out how to access the right tasks based on the categories. I've tried searching but haven't been able to find the answer anywhere.

jscs
  • 63,694
  • 13
  • 151
  • 195
Gando
  • 1
  • 1
    If you're just starting out, asking questions on Stack Overflow is not the place you need to be. You should find a good book or a series of online tutorials. Look at [the \[swift\] tag wiki for some resources](http://stackoverflow.com/tags/swift/info). If you're working on an Apple system, you could also take a look at [Good resources for learning ObjC](http://stackoverflow.com/q/1374660), which is really about Cocoa programming, and many of the items are updated to use Swift. Good luck! – jscs Nov 29 '17 at 20:40

1 Answers1

0

One way to do this would be to maintain 1 array and 1 dictionary. You could have a category array (in order to maintain a specific order), and then use the dictionary to look up the tasks that fall into that category. So it could look something like this:

var categories: [String] = ["Work", "Private"]
var tasks: [String : [String]] = ["Work" : ["Finish writing", "Go to lunch"], "Private" : ["Buy gifts for people who help me on Stack Overflow"]]

This way, in your tableView datasource methods you can set the numberOfSections to be categories.count, and when it's time to figure out the number of rows you can do something like this:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  //Get the category that corresponds to this section of the tableview
  let category = categories[section]
  //Return the number of tasks in that category
  return tasks[category].count
}

This is just one way to do this - I might argue the easiest, though in Swift you'll have to add/remove/access items in the dictionary safely to avoid crashes.

creeperspeak
  • 5,403
  • 1
  • 17
  • 38