Swift: Multiple intervals in single switch-case us

2019-03-08 09:24发布

问题:

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!

回答1:

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)")
}