4

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'

2
  • 1
    Where have you defined your deviceStatus? and what type of those objects (obj1, obj2, ...) are? Commented Nov 3, 2015 at 1:50
  • Possible duplicate of stackoverflow.com/q/31548855/994104 Commented Jun 21, 2016 at 20:44

1 Answer 1

12

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")
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.