Swift:二元运算符'=='不能应用于两个'() - > ()'操作数

时间:2018-01-31 02:28:52

标签: swift

尝试比较两个闭包时出错:

  

二元运算符'=='不能应用于两个'() - > ()'operands

我该怎么做?

例如:

enum SomeEnum {
   case caseOne
   case caseTwo(closure: () -> Void)
}

let e1 = SomeEnum.caseTwo(closure: {
    print("something 1")
})
let e2 = SomeEnum.caseTwo(closure: {
    print("something 2")
})

switch (e1, e2) {
case let (.caseTwo(l), .caseTwo(r)):
    return l == r // Binary operator '==' cannot be applied to two '() -> ()' operands
    break
default: 
    break
}

1 个答案:

答案 0 :(得分:1)

如果您想对具有关联值的枚举进行比较,则需要单独比较案例,以便您可以忽略具有相关值的案例的值。

enum SomeEnum {
    case caseOne
    case caseTwo(closure: () -> Void)
    case caseThree
}

let e1 = SomeEnum.caseTwo(closure: {
    print("something 1")
})
let e2 = SomeEnum.caseTwo(closure: {
    print("something 2")
})

switch (e1, e2) {
    case (.caseOne, .caseOne), (.caseThree, .caseThree):
        print("both something else")
    case (.caseTwo, .caseTwo):
        print("both caseTwo")
    default:
        print("not equal")
}