Swift元组开关案例:类型模式无法匹配类型的值



因此,我正在学习新工作的Swift并从事静态表视图,并决定尝试使用元组来跟踪选择哪个单元格。但是我遇到以下错误:

类型的表达模式'(章节:int,row:int)'无法匹配类型的值'(部分: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")
    }

真正令人困惑的是,当我使用以下" if"语句而不是开关语句时,所有程序都可以正常运行...

    if (cellIdentifier == CELL_ONE) {
        print("cell1")
    } else if (cellIdentifier == CELL_TWO) {
        print("cell2")
    } else if (cellIdentifier == CELL_THREE) {
        print("cell3")
    }

我发现比if语句更优雅的开关语句可以做到这一点吗?非常好奇为什么这不起作用。预先感谢!

解决方案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 struct及其初始化器即可创建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")
}

最新更新