Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check enum case of enum with associated values in Swift

Tags:

enums

swift

I'm trying to check the case of an enum that has associated values for each case like this:

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

I'm using if(status == deviceStatus.awake){ to check status case and am getting an error: Binary operator '==' cannot be applied to operands of type 'status' and '(obj1) -> status'

like image 996
JBaczuk Avatar asked Oct 15 '25 21:10

JBaczuk


1 Answers

You can use if case .awake = deviceStatus to check if deviceStatus is set to the awake enumeration value:

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")
}
like image 103
vacawama Avatar answered Oct 17 '25 13:10

vacawama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!