Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch that checks NSIndexPath's row and section

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?

like image 450
potato Avatar asked Mar 11 '16 17:03

potato


2 Answers

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
}
like image 111
matt Avatar answered Oct 08 '22 20:10

matt


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.

like image 32
heyfrank Avatar answered Oct 08 '22 20:10

heyfrank