Compiler error when comparing values of enum type with associated values?

[亡魂溺海] 提交于 2019-11-27 16:20:37

As you said in a comment, your enumeration type actually has associated values. In that case there is no default == operator for the enum type.

But you can use pattern matching even in an if statement (since Swift 2):

class MyClass {
    enum MyEnum {
        case FirstCase
        case SecondCase
        case ThirdCase(Int)
    }

    var state:MyEnum!

    func myMethod () {
        if case .FirstCase? = state {

        }
    }
}

Here .FirstCase? is a shortcut for .Some(MyEnum.FirstCase).

In your switch-statement, state is not automatically unwrapped, even if it is an implicitly unwrapped optional (otherwise you could not match against nil). But the same pattern can be used here:

switch state {
case .FirstCase?:
    // do something...
default:
    break
}

Update: As of Swift 4.1 (Xcode 9.3) the compiler can synthesize conformance to Equatable/Hashable for enums with associated values (if all their types are Equatable/Hashable). It suffices to declare the conformance:

class MyClass {
    enum MyEnum: Equatable {
        case firstCase
        case secondCase
        case thirdCase(Int)
    }

    var state:MyEnum!

    func myMethod () {
        if state  == .firstCase {
            // ...
        }
    }
}
class MyClass {
    enum MyEnum {
        case FirstCase
        case SecondCase
        case ThirdCase
    }

    var state: MyEnum!

    func myMethod()  {
        guard
            let state = state else { return }

        if state == MyEnum.FirstCase {
            // Do something
            print(true)
        } else {
             print(false)
        }
    }
}


let myClass = MyClass()
myClass.state = .FirstCase
myClass.myMethod()
myClass.state = .SecondCase
myClass.myMethod()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!