Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift元组开关大小写:类型的模式不能与类型的值匹配_Ios_Swift_Switch Statement_Tuples - Fatal编程技术网

Ios Swift元组开关大小写:类型的模式不能与类型的值匹配

Ios Swift元组开关大小写:类型的模式不能与类型的值匹配,ios,swift,switch-statement,tuples,Ios,Swift,Switch Statement,Tuples,因此,我正在学习swift以适应新的工作,并在一个静态表视图上工作,并决定尝试使用元组来跟踪选择的单元格。但是,我得到了以下错误: 类型为“(节:Int,行:Int)”的表达式模式无法与类型为“(节:Int,行:Int)”的值匹配 此错误是以下简化代码的结果 let ABOUTPROTECTIONCELL = (section: 1, row: 0) let cellIdentifier = (section: indexPath.section, row: indexPath.

因此,我正在学习swift以适应新的工作,并在一个静态表视图上工作,并决定尝试使用元组来跟踪选择的单元格。但是,我得到了以下错误:

类型为“(节:Int,行:Int)”的表达式模式无法与类型为“(节:Int,行: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”语句而不是switch语句时,一切正常,程序运行正常

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

有没有一种方法可以用switch语句来实现这一点,因为我发现它比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

只需使用
indepath
struct及其初始值设定项创建
aboutRovProtectionCell

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")
}

您的代码无法编译,因为元组不可
相等
。请参阅。如果它们不相等,为什么If语句要编译并运行?这让我很困惑。元组有一个
=
操作符,但元组不符合协议另外:Equatable协议保证存在
==运算符
,但
=
运算符并不意味着符合Equatable您的第一个案例可以像
开关单元标识符{case(ABOUTTROVPROTECTIONCELL.section,ABOUTTROVPROTECTIONCELL.row)一样重新编写:
@MidhunMP,是的,谢谢。