William Carty William Carty - 1 year ago 99
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"
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 Source

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

class YourTableViewDataSource {
    static let SectionTitles = [

    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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download