This is probably conflating unrelated concepts, but from a readability standpoint I think this theoretical syntax would be nice for that particular use case:
let isSuccess = result is .success
This is probably conflating unrelated concepts, but from a readability standpoint I think this theoretical syntax would be nice for that particular use case:
let isSuccess = result is .success
A related issue that also needs to be solved is a way of optionally extracting the enum's associated value in an expression (so whatever is held in .success
in this case).
Both of these syntaxes look pretty messy to me, comapred to x is y
or case x = y
(I still really hate case x = y
though, because it involves =
as a special comparison operator)
Not saying case paths wouldn't be useful to have, but I think that should be considered an unrelated feature to what I'm asking for here. You make a good point about not having a similar way to extract payloads, too.
Not nice but there is a way to convert "switch" or "if" into expression:
enum E {
case foo, bar(Int)
}
let isFoo: Bool = {
switch f {
case .foo: return true
default: return false
}
}()
squeezed into a single line:
let isFoo: Bool = { if case .foo = f { return true } else { return false }}()
I agree, looks like a language hole. Another possible syntax:
let isFoo = f.foo != nil
let isBar = f.bar != nil
let x: E? = f.foo // x contains E.foo or nil
let y: E? = f.bar // y contains nil or E.bar(xxx)
I'm not fond of any of these syntaxes personally, but I do appreciate you brainstorming with me!
The switch-case on a single line (or even in a closure like that) is a code smell and indicative of a hole in the language; I would sooner extend whatever it was I was switching over to add a property before I did that
The second idea is just… weird to me. Doesn't make sense to use dot syntax to access something that isn't a type or property. This needs it's own keyword syntax. I would love to just use is
Not so crazy, we have a precedent of e.rawValue
Another possibility:
enum E: MetaCaseIterable {
case foo(Int), bar
}
// MetaCaseIterable (better name needed) is a magic protocol that implements this under the hood:
extension E {
enum MetaCase { case foo, bar }
var metaCase: MetaCase {
switch self {
case .foo(_): return .foo
case .bar: return .bar
}
}
static let allMetaCases: [MetaCase] = [.foo, .bar] // better name needed
}
// usage:
var e: E = ...
let isFoo = e.metaCase == .foo
E.allMetaCases == [.foo, .bar]
This is a property, it's just a compiler synthesized one for enums with raw values.