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?
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
}