Enums… those lovely little beasts of many uses. I really do like associated enums. Well, at least, I really like the idea of associated enums.
The problem: they really suck to work with.
Take for example you simply want to validate that an enum you got back is a specific enum case.
enum Simple {
case SoEasy
case Peasy
}
func simple() -> Simple { return .SoEasy }
func testSimple() {
assertme(simple() == .SoEasy)
}
This is a cake walk with normal enums. But…
enum DoYou {
case ReallyWantToHurtMe(Bool)
case ReallyWantToMakeMeCry(Bool)
}
func doyou() -> DoYou { return .ReallyWantToHurtMe(true) }
func testChump() {
assertme(doyou() == .ReallyWantToHurtMe)
}
GAH! Ok…
func testChump() {
assertme(case .ReallyWantToHurtMe = doyou())
}
Oh… the case
syntax isn’t a real expression…
func testChump() {
if case .ReallyWantToHurtMe = doyou() { assertme(false) }
}
Yeah… that’s really less than ideal.
This is where I just get really freaking tired of working with associated enums and I do one of two things:
- Convert the associated enum into a struct that holds the values and a enum that is just the simple types. 2. Add getters for every case that returns an optional.
The first option has the severe limitation of only really working when the cases hold the same data types or nearly the same. It’s also a bit more annoying.
The second option is just super annoying to have to do. It signals a significant design issue with them. It’s also just a waste of time as well.
So this is what I do:
enum DoYou {
case ReallyWantToHurtMe(Bool)
case ReallyWantToMakeMeCry(Bool)
var reallyWantToHurtMe: Bool? {
if case let .ReallyWantToHurtMe(value) = doyou() { return value }
return nil
}
var reallyWantToMakeMeCry: Bool? {
if case let .ReallyWantToMakeMeCry(value) = doyou() { return value }
return nil
}
}
func testChump() {
assertme(doyou().reallyWantToHurtMe != nil)
}
/cry