Mark A. Donohoe
Mark A. Donohoe

Reputation: 30378

What is the easiest way to test if an enum-based variable is *not* equal to a specific case with an associated value?

We have the following enum and variable

enum DisplayState{
    case loading
    case loaded(ViewModel)
    case noResults
    case error
}

var displayState:DisplayState = .loading

We want to test if we're in any state other than loaded.

Since there is an associated value, this of course doesn't work...

if displayState != .loaded {
    // Do something
}

But I'm hoping to find something else besides either of these...

switch displayState{
    case .loaded: break
    default: // Do something
}

or

if case .loaded = displayState {} else {
    // Do something
}

So what's the simplest way to test for this case?

Upvotes: 5

Views: 385

Answers (1)

Nader
Nader

Reputation: 1148

Try that:

enum DisplayState {
    case loading
    case loaded(ViewModel)
    case noResults
    case error

    var isLoaded: Bool {
        switch self {
        case .loaded:
            return true
        default:
            return false
        }
    }
}

var displayState: DisplayState = .loading

if displayState.isLoaded {
    // code
}

Upvotes: 3

Related Questions