Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

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
    }
}
like image 816
KevinS Avatar asked Jul 24 '16 03:07

KevinS


3 Answers

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

private enum TableSection: 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 TableSection.horizontalSection.rawValue:
        return firstArray.count

    case TableSection.verticalSection.rawValue:
        return secondArray.count

    default:
        return 0
    }
}
like image 137
Jeff Lewis Avatar answered Oct 20 '22 00:10

Jeff Lewis


Ok, I figured it out, thanks @tktsubota for pointing me in the right direction. I'm pretty new to Swift. I looked into .rawValue and made some changes:

private enum TableSections: Int {
    case HorizontalSection = 0
    case VerticalSection = 1
}

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
    }
}
like image 4
KevinS Avatar answered Oct 20 '22 00:10

KevinS


Jeff Lewis did it right, to elaborate on that and give the code litlle bit of more readiness -> my way of handling these things is to:

  1. Instantiate enum with the raw value -> section index

guard let sectionType = TableSections(rawValue: section) else { return 0 }

  1. Use switch with section type

switch sectionType { case .horizontalSection: return firstArray.count case .verticalSection: return secondArray.count }

like image 6
deathhorse Avatar answered Oct 20 '22 00:10

deathhorse