因此,我正在学习swift以获得新工作并处理静态表视图,并决定尝试使用元组来跟踪已选择的单元格。但是我收到以下错误:
类型'(section:Int,row:Int)'的表达模式不能匹配类型'(section:Int,row:Int)'
的值
此错误是以下简化代码的结果
let ABOUTPROTECTIONCELL = (section: 1, row: 0)
let cellIdentifier = (section: indexPath.section, row: indexPath.row)
switch cellIdentifier {
case ABOUTPROTECTIONCELL:
print("here")
default:
print("bleh")
}
真正令人困惑的是,当我使用以下"如果"语句而不是switch语句一切正常,程序运行良好......
if (cellIdentifier == CELL_ONE) {
print("cell1")
} else if (cellIdentifier == CELL_TWO) {
print("cell2")
} else if (cellIdentifier == CELL_THREE) {
print("cell3")
}
有没有办法用switch语句执行此操作,因为我发现它比if语句更优雅?非常好奇为什么这不起作用。提前谢谢!
答案 0 :(得分:2)
解决方案1
let ABOUTTROVPROTECTIONCELL = (section: 1, row: 0)
let cellIdentifier = (section: indexPath.section, row: indexPath.row)
switch cellIdentifier {
case (ABOUTTROVPROTECTIONCELL.section, ABOUTTROVPROTECTIONCELL.row):
print("here")
default:
print("bleh")
}
解决方案2
只需使用IndexPath
结构及其初始值设定项即可创建ABOUTTROVPROTECTIONCELL
let ABOUTTROVPROTECTIONCELL = IndexPath(row: 0, section: 1)
let cellIdentifier = indexPath // Not necessary, you can just use indexPath instead
switch cellIdentifier {
case ABOUTTROVPROTECTIONCELL:
print("here")
default:
print("bleh")
}
解决方案3
为你的元组实现~=
func:
typealias IndexPathTuple = (section: Int, row: Int)
func ~=(a: IndexPathTuple, b: IndexPathTuple) -> Bool {
return a.section ~= b.section && a.row ~= b.row
}
let ABOUTTROVPROTECTIONCELL = (section: 1, row: 0)
let cellIdentifier = (section: indexPath.section, row: indexPath.row)
switch cellIdentifier {
case ABOUTTROVPROTECTIONCELL:
print("here")
default:
print("bleh")
}