Ezra
Ezra

Reputation: 670

Swift: Binary operator '==' cannot be applied to two '() -> ()' operands

Got an error when try to compare two closures:

Binary operator '==' cannot be applied to two '() -> ()' operands

How should I do this?

For example:

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
}

Upvotes: 3

Views: 3014

Answers (1)

Samah
Samah

Reputation: 1234

If you want to do comparisons of enums that have associated values, you will need to individually compare cases so that you can ignore the values of those that have them.

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

Upvotes: 3

Related Questions