我想设置一个 switch 语句来检查 NSIndexPath
的值。 NSIndexPath
是一个类,它由(除其他外)部分和行组成(indexPath.row, indexPath.section
)
这就是我如何制定一个 if 语句来同时检查一行和一个部分:
if indexPath.section==0 && indexPath.row == 0{
//do work
}
什么是快速切换翻译?
最佳答案
一种方式(之所以可行,是因为 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
}
关于swift - 检查 NSIndexPath 的行和部分的开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35945923/