Checking the case of an enum (in Tests particularly)

Currently if an enum has an associated value (or isn’t Equatable), the way to check if it is that case is quite verbose:

enum Status {
    case code(Int)
    case failed
}

let isCode = if case .code = status { true } else { false }

This is fairly ok in normal code as you typically will be doing something more than returning true or false in the branches of the if.

However it’s quite cumbersome in Testing and doing an if and then true and false is quite a code smell usually. Also you don’t get the nice expansion of variables if the test fails

let isCode = if case .code = status { true } else { false }
#expect(isCode)

// … Another test checking for failed, much more readable but inconsistent with above
#expect(status == .failed)

It would be far nicer if there was some syntax sugar for it such as:

#expect(status is case .code)

Then the macro could expand the status variable and show what the value of it is if it fails.

You may find this prior pitch of use:

It has also done the work of linking to quite a bit—and probably by no means all—of the prior discussions, which have evidently taken place about every year for at least the past decade:

Since that post, at least one further discussion on the topic occurred in 2024.

As you'll see from the linked thread, the language steering group provided feedback on the topic and how to proceed from here, but it's a bit of a heavy lift:

4 Likes