Swift: Multiple intervals in single switch-case using tuple

iiFreeman picture iiFreeman · Aug 6, 2014 · Viewed 41.4k times · Source

Have a code like:

switch (indexPath.section, indexPath.row) {
    case (0, 1...5): println("in range")
    default: println("not at all")
}

The question is can I use multiple intervals in second tuple value?

for non-tuple switch it can be done pretty easily like

switch indexPath.section {
case 0:
    switch indexPath.row {
    case 1...5, 8...10, 30...33: println("in range")
    default: println("not at all")
    }
default: println("wrong section \(indexPath.section)")
}

Which separator should I use to separate my intervals inside tuple or it's just not gonna work for tuple switches and I have to use switch inside switch? Thanks!

Answer

drewag picture drewag · Aug 6, 2014

You have to list multiple tuples at the top level:

switch (indexPath.section, indexPath.row) {
    case (0, 1...5), (0, 8...10), (0, 30...33):
        println("in range")
    case (0, _):
        println("not at all")
    default:
        println("wrong section \(indexPath.section)")
}