2

I have some confusion with using a switch statement to a UITableView. I am attempting to set my numberOfRowsInSection function, but I am getting an error with my switch statement "Binary operator '~=' cannot be applied to operands of type 'Bool' and 'Int'':

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

    switch section {
        case section == 0:
            return provinces.count
        case section == 1:
            return territories.count
        default:
            return 0
    }
}

I am confused because section is declared as an Int, yet the error seems to indicate it is a BOOL. When i use an if-else statement, it compiles just fine:

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return provinces.count
    } else {
        return territories.count
    }
}

What am I missing?

luk2302
  • 55,258
  • 23
  • 97
  • 137
Andrew Walz
  • 890
  • 2
  • 8
  • 27
  • 4
    Unrelated to your concrete problem, but note that simply returning zero in the default case hides programming errors (assuming that this case "should not occur"). As an alternative, consider to throw a `fatalError()` in that case. See http://stackoverflow.com/questions/30189505/missing-return-uitableviewcell for an example. – Martin R Jun 20 '15 at 21:11
  • Thanks for the tip! I wondered how to handle the default case in the event it would "never" occur. – Andrew Walz Jun 20 '15 at 21:16

1 Answers1

5

Remove the section ==

switch section {
    case 0:
        return provinces.count
    case 1:
        return territories.count
    default:
        return 0
}

The cases represent the values of section. But your code would not make sense because the cases would be evaluated to either true or false, which are not possible values for section. Those values would be bools and therefore the error message talks about bools.

luk2302
  • 55,258
  • 23
  • 97
  • 137