【问题标题】:Swift: Multiple intervals in single switch-case using tupleSwift:使用元组在单个开关案例中的多个间隔
【发布时间】:2014-09-29 16:02:15
【问题描述】:

有这样的代码:

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

问题是我可以在第二个元组值中使用多个区间吗?

对于非元组切换,它可以很容易地完成,就像

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

我应该使用哪个分隔符来分隔元组内的间隔,否则它不适用于元组开关,我必须在开关内使用开关?谢谢!

【问题讨论】:

    标签: ios swift switch-statement tuples xcode6


    【解决方案1】:

    您必须在顶层列出多个元组:

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

    【讨论】:

    • 完美运行!太感谢了!现在无法理解我是怎么想出来的!谢谢!
    • 如果您没有对它们使用fallthrough 语句,那么将最严格的情况放在首位是很重要的。开关从上到下评估案例,而不是完美匹配的案例。
    • 这太棒了!您在 doc 中哪里找到的?
    • @drewag 在单一情况下使用letvar 是否可行?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    相关资源
    最近更新 更多