Tometoyou
Tometoyou

Reputation: 8376

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?

Upvotes: 0

Views: 74

Answers (2)

fiks
fiks

Reputation: 1045

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)

Upvotes: 1

Bhoomi Jagani
Bhoomi Jagani

Reputation: 2423

Replace line

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

with

let e : NSError!
let locationAvailable = locationManager.getCurrentState() != LocationState.LocationUnavailable(e)

Upvotes: 0

Related Questions