Tometoyou Tometoyou - 1 year ago 64
iOS Question

Comparing enums returns error

I have an enum defined as follows:

enum LocationState : Equatable {
case Idle
case RetrievingLocation
case RetrievedLocation(CLLocation)
case PermissionsDenied(String)
case LocationUnavailable(NSError)

I have added the equatable protocol function as follows

func == (lhs: LocationState, rhs: LocationState) -> Bool {
return lhs == rhs

Now I want to determine if a variable that holds an enum is equal to a certain enum:

let locationAvailable = locationManager.getCurrentState() != .LocationUnavailable(_)

However, this gives the error
'_' can only appear in a pattern or on the left side of an assignment.

How do I fix this?


You need to pass a value when comparing against enum with associated values.

I would suggest to change the declaration of the enum to following: enum LocationState : Equatable { case Idle case RetrievingLocation case RetrievedLocation(Int) case PermissionsDenied(String) case LocationUnavailable(NSError?) }

And then you compare in the following way:

let locationAvailable = locationManager.getCurrentState() != .LocationUnavailable(nil)

In case you want to compare against specific error, you need to pass it as an argument:

let locationAvailable = locationManager.getCurrentState() != .LocationUnavailable(myError)