There's been a bit of discussion on this in the past, but as there's been no movement I thought I'd bring it up again. Given an enumeration with an associated type;
enum MyEnumeration {
case aaa
case bbb(String)
case ccc
}
One can do...
let e = MyEnumeration("Dummy")
if case MyEnumeration.bbb = e {
print("matches")
}
Where inside of the if statement the case (let) obviously evaluates to true. Our enumeration value is some form of a bbb
. Great.
However, try to do something like...
let publisher = PassthroughSubject<MyEnumeration, Never>()
publisher
.filter { case MyEnumeration.bbb = $0 }
.sink { e in
print(e)
}
And you'll get an error. What one is forced to do, instead, is...
let publisher = PassthroughSubject<MyEnumeration, Never>()
publisher
.filter {
if case TestEnumeration.bbb = $0 {
return true
}
return false
}
.sink { e in
print(e)
}
Which is ugly, verbose, and would be completely unnecessary if said case would simply evaluate as a boolean. Which it obviously can do, as shown in the earlier example.
Another, entirely too common situation is wanting something like...
extension MyEnumeration {
var isBBB: Bool { case .bbb = self }
}
Nope. Back once more to our previous over-elaboration.
extension MyEnumeration {
var isBBB: Bool {
if case .bbb = self {
return true
}
return false
}
}
Which, when added, let's us do...
.filter { $0.isBBB }
Which is where we wanted to be in the first place.
Heaven help you if you want something like...
extension MyEnumeration {
var isSomeSubset: Bool {
case .bbb = self || case .ccc = self
}
}
Currently your best option there is some variation of...
extension MyEnumeration {
var isSomeSubset: Bool {
switch self {
case .bbb, .ccc:
return true
default:
return false
}
}
}
Again, ungainly and totally unnecessary.
Allowing the case to evaluate to boolean anywhere and everywhere would solve the problem, and while creating the least impact.
But as long as I'm making a Christmas wish, what I'd really like is to be able to do something like...
.filter { $0 is .bbb }
We already know the type, and as such requiring the case MyEnumeration.
in case MyEnumeration.bbb = $0
is again overly verbose. Further, if all we care about is the pattern match then the case let assignment syntax no longer makes sense either.
And finally, an easy to use syntax would pretty much obviate the need to create supporting code like MyEnumeration.isBBB in the first place. (Or the need to synthesize them, as some proposals have suggested.)
Any thoughts on this?