17

I would like to set a switch statement that checks for a value if NSIndexPath. NSIndexPath is a class and it consists(among other things) of section and row (indexPath.row, indexPath.section)

this is how I would formulate an if statement to check for a row and a section at the same time:

if indexPath.section==0 && indexPath.row == 0{
//do work
}

What is swift switch translation for this?

potato
  • 4,479
  • 7
  • 42
  • 99

3 Answers3

34

One way (this works because NSIndexPaths themselves are equatable):

switch indexPath {
case NSIndexPath(forRow: 0, inSection: 0) : // do something
// other possible cases
default : break
}

Or you could just test against integers, using a tuple pattern:

switch (indexPath.section, indexPath.row) {
case (0,0): // do something
// other cases
default : break
}

Another trick is to use switch true and the same condition you're already using:

switch true {
case indexPath.row == 0 && indexPath.section == 0 : // do something
// other cases
default : break
}

Personally, I would use nested switch statements where we test against indexPath.section on the outside and indexPath.row on the inside.

switch indexPath.section {
case 0:
    switch indexPath.row {
    case 0:
        // do something
    // other rows
    default:break
    }
// other sections (and _their_ rows)
default : break
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
20

Just use IndexPathinstead of NSIndexPath and do the following:

Tested in Swift 3 and 4:

switch indexPath {
case [0,0]: 
    // Do something
case [1,3]:
    // Do something else
default: break
}

The first integer is the section, the second one is the row.

EDIT:

I just noticed that this method above isn't as powerful as the tuple matching method of matt's answer.

If you do it with a tuple, you can do something like this:

switch (indexPath.section, indexPath.row) {
case (0...3, let row):
    // this matches sections 0 to 3 and every row + gives you a row variable
case (let section, 0..<2):
    // this matches all sections but only rows 0-1
case (4, _):
    // this matches section 4 and all possible rows, but ignores the row variable
    break
default: break
}

See https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html for complete documentation of possible switch statement usages.

heyfrank
  • 5,291
  • 3
  • 32
  • 46
0

An Alternative way is to combine switch with if case

switch indexPath.section {
case 0:
    if case 0 = indexPath.row {
        //do somthing
    } else if case 1 = indexPath.row  {
          //do somthing
        // other possible cases
    } else { // default
        //do somthing
    }
case 1:
// other possible cases
default:
    break
}
byaruhaf
  • 4,128
  • 2
  • 32
  • 50