4

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?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
  • 1
    You're a source of consistently good questions. This one's interesting! I typically make helper computed vars, like `isLoading`, `isLoaded`, `hasNoResults`, `isErrored`, so I would use one of those. – Alexander Apr 30 '18 at 21:09
  • Thanks for the kudos! Swift is such a great language, which is why this surprised me that it has to be so convoluted for these simple tests where you don't care what the value is. I feel I should be able to test against a value and just ignore its type though. I may have to visit Swift Evolution to see if there was rationale behind not doing that. I mean you can pattern-match against it while ignoring the associated values, so why not overload the equality to do the same? – Mark A. Donohoe Apr 30 '18 at 21:18
  • Yeah, I wish there was a sort of "metaenum" made for enums with associated values, which lets you talk about the cases without particular regard for the associated values. – Alexander Apr 30 '18 at 21:20

1 Answers1

3

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
}
Nader
  • 1,120
  • 1
  • 9
  • 22
  • Interesting approach. It's a shame you have to decorate your enums like this. I wonder why the Swift team didn't just allow the simple != check. I mean you can pattern match against it! But this is a good work-around. Lemme leave it open a bit longer to see if someone comes up with any alternatives. If not, I'll mark this as accepted. – Mark A. Donohoe Apr 30 '18 at 21:15
  • @MarqueIV I agree, however computed vars inside your enum is probably your best bet. – Nader Apr 30 '18 at 22:18