William Carty William Carty - 1 month ago 7
Swift Question

Using an array of Strings to set section names using titleForHeaderInSection in Swift

So my goal is as the title states, is to use an array of strings to set the titles for sections I am currently using a switch statement

switch section
{
case 0:
return "Home"
case 1:
return "Work "
case 2:
return "Weekend "
case 4:
return "Uncatagorized"
default:
return ""
}


the reason I would like to use an array is because I would like to add to the array from the front in to create a new section. Any suggestions or ideas of a better way.

Answer

Just use the section parameter to subscript an array stored as a static class constant array of your choosing.

class YourTableViewDataSource {
    static let SectionTitles = [
        "Home",
        "Work",
        "Weekend",
        "Uncatagorized"
    ]

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        guard SectionTitles.indices ~= section else {
            print("No section title for this section")
            return nil
        }

        return SectionTitles[section]
    }
}