Hacker News new | ask | show | jobs
by bbatsell 398 days ago
The HTTPStatus enum example is a good one, but the backtick syntax is _rough_. I would only ever use the Type.case form in practice. The test stuff is basically a way to create BDD-style test names, which is kind of just a preference thing. I can’t envision myself using it for anything other than weird case names (I already use case `default` quite a lot because it’s such a useful word), but maybe some interesting DSLs can come out of it? I would not have prioritized that change personally.
3 comments

The HTTP status enum example is a _terrible_ one. If you need to represent HTTP statuses and call them by their integer names, why not just pass the damn integer itself? It's exactly what you get in `HTTPURLResponse.statusCode`, and you can already `switch` against it. Already not looking forward to the code that undiscerning devs will mindlessly write just because someone with a huge following wrote a blog.
You can’t exhaustively handle an enum with just an integer.
You want to exhaustively handle all 500 valid HTTP status codes (cf. RFC 9110)?
Exhaustive matching doesn’t necessarily mean you handle every case separately, but it means you aren’t going to get cases you don’t know about sneaking in. With a bare int you can get values outside a range and the compiler won’t help
Either you’re unaware or you’re arguing in bad faith, but you can switch against integers and pattern-match within integer ranges. The consequences of receiving an unexpected status code is the same—you handle it in the default case, as you would when decoding to an HTTPStatus enum fails.
Way to start of the comment by being uncivil. You could have made the exact same point without being a jerk about it.

But it’s common to only want to support specific response codes in a context, and people do use enums for that. It’s a fairly common paradigm, and an enum will do all those validations for you so you don’t forget.

When you receive an HTTP response, it can contain a status value outside the valid range as well. So you have to handle those one way or the other.

Regarding the int type, a better solution would be to provide the ability to define a restricted integer type, so that the compiler can help.

Okay? So you cast it to the enum and instantly know it’s not a case you support.

It’s built in validation.

The backtick syntax for enums is rough, and typing out the full Type.case form negates one of Swift’s niceties (the ability to just type .case if the compiler can tell which enum is in use).
I would not have even approved it. But that's just me.