pot*_*ato 14 switch-statement nsindexpath swift
我想设置一个switch语句来检查一个值if NSIndexPath.NSIndexPath是一个类,它包括(和其他)的section和row(indexPath.row, indexPath.section)
这就是我如何制定一个if语句来同时检查一行和一个部分:
if indexPath.section==0 && indexPath.row == 0{
//do work
}
Run Code Online (Sandbox Code Playgroud)
什么是swift开关翻译呢?
mat*_*att 28
一种方法(这是有效的,因为NSIndexPaths本身是等价的):
switch indexPath {
case NSIndexPath(forRow: 0, inSection: 0) : // do something
// other possible cases
default : break
}
Run Code Online (Sandbox Code Playgroud)
或者你可以使用元组模式测试整数:
switch (indexPath.section, indexPath.row) {
case (0,0): // do something
// other cases
default : break
}
Run Code Online (Sandbox Code Playgroud)
另一个技巧是使用switch true和你已经使用的相同条件:
switch true {
case indexPath.row == 0 && indexPath.section == 0 : // do something
// other cases
default : break
}
Run Code Online (Sandbox Code Playgroud)
就个人而言,我会使用嵌套 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
}
Run Code Online (Sandbox Code Playgroud)
fl0*_*034 15
只需使用IndexPath而不是NSIndexPath执行以下操作:
在Swift 3和4中测试过:
switch indexPath {
case [0,0]:
// Do something
case [1,3]:
// Do something else
default: break
}
Run Code Online (Sandbox Code Playgroud)
第一个整数是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
}
Run Code Online (Sandbox Code Playgroud)
有关可能的语句用法的完整文档,请参阅https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.htmlswitch.
| 归档时间: |
|
| 查看次数: |
5937 次 |
| 最近记录: |