Mike Mike - 7 months ago 8
Swift Question

My codes do not work for sections in TableView

I need to set sections in a TableView. Each section has different value types, please see my codes. But it doesn't work. Please advise correct way to set up values in sections. Please refer to screenshot for error message. Note: I deleted ")" at the end of var detailsInSection because it won't show correctly.

error message

var sectionTitles = ["WebSite", "Date Saved", "Document Used","Add Notes"]

var detailsInSection = [([String], [NSDate],[AnyObject],[String])]()

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return detailsInSection[section].count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("DetailsCell")

cell?.textLabel!.text = detailsInSection[indexPath.section][indexPath.row]

return cell!
}

Answer
var detailsInSection = [([String], [NSDate],[AnyObject],[String])]

The above is an array of tuple. I'm guessing from the rest of your code that you want an array of arrays.

var detailsInSection = [[String](), [NSDate](), [AnyObject](), [String]()]

Your array would have 4 elements, each of which is an array.

If you want to handle the different types then use a switch statement.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("DetailsCell")!
    switch indexPath.section {
        case 0:
cell.textLabel!.text = detailsInSection[indexPath.section][indexPath.row]
        case 1:
             let date = detailsInSection[indexPath.section][indexPath.row]
             // Do some date formatting etc
             cell.textLabel!.text = PUT YOUR FORMATTED DATE HERE
        case 2:
             // Do any type casting etc.
             let object = detailsInSection[indexPath.section][indexPath.row] 
             // Convert object to whatever is needed in text format.
             cell.textLabel!.text = PUT YOUR OUTPUT HERE
        case 3:
             // This is a string so just assign it.
             cell.textLabel!.text = detailsInSection[indexPath.section][indexPath.row]
        default:
             // What to do here? Should never happen.
    }
    return cell
}
Comments