Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27133

Use enum swift issue

I have enum:

enum VAXSettingsCells : Int
  {
    case SwitchModeCell = 0
    case SwitcherCell = 1
    case NewProgramCell = 2
    case CreatedProgramCell = 3
  }

which I use in my UITableView delegate:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
  {
    let cellID = VAXSettingsCells(rawValue: indexPath.row)

    switch cellID {
    case .SwitchModeCell:
      let cell = theTableView.dequeueReusableCellWithIdentifier(VAXSettingsSwitchModeCell.reusableCellIdentifier()) as! VAXSettingsSwitchModeCell
      cell.delegate = self
      return cell

But I get some error:

Enum case 'SwitchModeCell' not found in type 'VAXSettingsViewController.VAXSettingsCells?'

How to get rid of this error? Actually I can use raw values to get int and it will work but I want to use enum data instead as I don't want to use default case of switch.

Upvotes: 2

Views: 637

Answers (2)

OOPer
OOPer

Reputation: 47886

As already noted, your cellID is of type VAXSettingsCells?, it's Optional and you cannot use it directly in switch-case statement.

Optional binding (if-let) would be a preferred solution, but you have another option. Use postfix ? notation.

You can write your switch statement as:

    let cellID = VAXSettingsCells(rawValue: indexPath.row)

    switch cellID {
    case .SwitchModeCell?:
        let cell = theTableView.dequeueReusableCellWithIdentifier(VAXSettingsSwitchModeCell.reusableCellIdentifier()) as! VAXSettingsSwitchModeCell
        cell.delegate = self
        return cell
    //...

Remember postfix ? notation case value?: is just a shorthand of case .Some(value):. You'd better see this thread.

Upvotes: 1

Sahil
Sahil

Reputation: 9226

You first need to unwrap the VAXSettingsCells return optional value.

If you define an enumeration with a raw-value type, the enumeration automatically receives an initializer that takes a value of the raw value’s type (as a parameter called rawValue) and returns either an enumeration case or nil

if let cellID = VAXSettingsCells(rawValue: indexPath.row) {
switch cellID {

case .SwitchModeCell:
  // do whatever you want to do here
default: break

}

}

and In the example above, VAXSettingsCells has an implicit raw value of 0 for SwitchModeCell, and so on. so you don't need to give it explicitly. simply use

enum VAXSettingsCells : Int
{
 case SwitchModeCell
 case SwitcherCell
 case NewProgramCell
 case CreatedProgramCell
}

You access the raw value of an enumeration case with its rawValue property.

Upvotes: 4

Related Questions