检查 NSIndexPath 的行和部分的开关

switch that checks NSIndexPath's row and section

我想设置一个 switch 语句来检查一个值 if NSIndexPathNSIndexPath 是一个 class,它由(除其他外)部分和行组成 (indexPath.row, indexPath.section)

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

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

什么是 swift switch 翻译?

一种方式(之所以可行,是因为 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
}

就个人而言,我会使用 nested 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
}

只需使用 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
}

有关可能的 switch 语句用法的完整文档,请参阅 https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html

另一种方法是将 switchif 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
}