代码之家  ›  专栏  ›  技术社区  ›  byaruhaf

有没有一种更简洁的方式来匹配这个代码而不必付出可读性的代价[复制]

  •  -1
  • byaruhaf  · 技术社区  · 5 年前

    NSIndexPath . 是一个类,它由节和行组成( indexPath.row, indexPath.section

    这就是我将如何制定一个if语句来同时检查一行和一节:

    if indexPath.section==0 && indexPath.row == 0{
    //do work
    }
    

    这是什么意思?

    0 回复  |  直到 9 年前
        1
  •  34
  •   matt    9 年前

    一种方法(这是因为NSIndexPaths本身是相等的):

    switch indexPath {
    case NSIndexPath(forRow: 0, inSection: 0) : // do something
    // other possible cases
    default : break
    }
    

    switch (indexPath.section, indexPath.row) {
    case (0,0): // do something
    // other cases
    default : break
    }
    

    switch true 和你现在使用的条件一样:

    switch true {
    case indexPath.row == 0 && indexPath.section == 0 : // do something
    // other cases
    default : break
    }
    

    就我个人而言,我会用 嵌套的 switch 我们测试的语句 indexPath.section indexPath.row

    switch indexPath.section {
    case 0:
        switch indexPath.row {
        case 0:
            // do something
        // other rows
        default:break
        }
    // other sections (and _their_ rows)
    default : break
    }
    
        2
  •  19
  •   heyfrank    7 年前

    只是使用 IndexPath 而不是 NSIndexPath 并执行以下操作:

    Swift 3和4

    switch indexPath {
    case [0,0]: 
        // Do something
    case [1,3]:
        // Do something else
    default: break
    }
    

    第一个整数是 section ,第二个是 row .

    我只是注意到上面的这个方法没有matt答案的元组匹配方法强大。

    如果你用一个 元组

    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
    }
    

    看到了吗 https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html 对于可能的 switch 语句用法。

        3
  •  0
  •   byaruhaf    5 年前

    另一种方法是合并 switch 具有 if case

    switch indexPath.section {
    case 0:
        if case 0 = indexPath.row {
            //do somthing
        } else if case 1 = indexPath.row  {
              //do somthing
            // other possible cases
        } else { // default
            //do somthing
        }
    case 1:
    // other possible cases
    default:
        break
    }