如何在Swift中检查具有关联值的枚举的枚举情况

时间:2015-11-03 01:36:24

标签: swift enums

我正在尝试检查枚举的情况,该枚举具有每个案例的关联值,如下所示:

enum status {
    case awake(obj1)
    case sleeping(obj2)
    case walking(obj3)
    case running(obj4)
}

我正在使用if(status == deviceStatus.awake){检查状态并收到错误:Binary operator '==' cannot be applied to operands of type 'status' and '(obj1) -> status'

1 个答案:

答案 0 :(得分:5)

您可以使用if case .awake = deviceStatus检查deviceStatus是否设置为awake枚举值:

class Obj1 { }
class Obj2 { }
class Obj3 { }
class Obj4 { }

enum Status {
    case awake(Obj1)
    case sleeping(Obj2)
    case walking(Obj3)
    case running(Obj4)
}

let deviceStatus = Status.awake(Obj1())

if case .awake = deviceStatus {
    print("awake")
} else if case .sleeping = deviceStatus {
    print("sleeping")
}

// you can also use a switch statement

switch deviceStatus {
case .awake:
    print("awake")
case .sleeping:
    print("sleeping")
default:
    print("something else")
}