Matrosov Alexander Matrosov Alexander - 3 months ago 18
iOS Question

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.

Answer

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.

Comments