我正在尝试检查枚举的情况,该枚举具有每个案例的关联值,如下所示:
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'
答案 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")
}