【问题标题】:How to check enum case of enum with associated values in Swift如何在 Swift 中使用关联值检查枚举的枚举大小写
【发布时间】:2015-11-03 01:36:24
【问题描述】:

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

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'

【问题讨论】:

标签: swift enums


【解决方案1】:

您可以使用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")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 2020-09-15
    相关资源
    最近更新 更多