KevinS KevinS - 4 months ago 24
iOS Question

How to use an enum and switch() with UITableViewController in Swift

My UITableView has two sections, so I created an enum for them:

private enum TableSections {
HorizontalSection,
VerticalSection
}


How do I switch with the "section" var passed in numberOfRowsInSection delegate method? It seems that I need to cast "section" to my enum type? Or is there a better way to accomplish this?

The error is "Enum case "HorizontalSection" not found in type 'int'.

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

switch section {

case .HorizontalSection:
return firstArray.count

case .VerticalSection:
return secondArray.count

default
return 0
}
}

Answer

In order to do this, you need to give your enum a type (Int in this case):

private enum TableSections: Int {
    HorizontalSection,
    VerticalSection
}

This makes it so that 'HorizontalSection' will be assigned the value 0 and 'VerticalSection' will be assigned the value 1.

Now in your numberOfRowsInSection method you need to use .rawValue on the enum properties in order to access their integer values:

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

    switch section {

    case TableSections.HorizontalSection.rawValue:
        return firstArray.count

    case TableSections.VerticalSection.rawValue:
        return secondArray.count

    default:
        return 0
    }
}