【问题标题】:Swift tuple switch case : pattern of type cannot match values of type [duplicate]Swift tuple switch case:类型的模式不能匹配类型的值[重复]
【发布时间】:2017-09-29 19:34:45
【问题描述】:

因此,我正在为新工作学习 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")
    }

真正令人困惑的是,当我使用以下“if”语句而不是 switch 语句时,一切正常,程序运行正常......

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

有没有办法用 switch 语句来做到这一点,因为我发现它比 if 语句更优雅?很好奇为什么这不起作用。提前致谢!

【问题讨论】:

  • 您的代码无法编译,因为元组不是Equatable。见Why can't I use a tuple constant as a case in a switch statement
  • 如果它们不相等,为什么 if 语句会编译并运行?这让我很困惑。
  • 元组有==运算符,但元组不符合协议。 – 另外:Equatable 协议保证 == operator 的存在,但 == 运算符并不意味着符合 Equatable

标签: ios swift switch-statement tuples


【解决方案1】:

解决方案 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")
}

【讨论】:

  • 你的第一个案例可以像switch cellIdentifier { case (ABOUTTROVPROTECTIONCELL.section, ABOUTTROVPROTECTIONCELL.row):一样重写
  • @MidhunMP,是的,谢谢。
猜你喜欢
  • 2016-03-02
  • 2018-07-15
  • 2020-12-12
  • 2017-11-22
  • 1970-01-01
  • 2019-06-03
  • 2015-08-04
  • 2010-10-25
  • 2019-04-06
相关资源
最近更新 更多