Home > Software engineering >  Use Guard to trap all enum states other than one
Use Guard to trap all enum states other than one

Time:02-28

Hitting a block on using a guard. Ideally want to do a guard statement that traps all enum states other than one, so would be something like:

guard case .notInUse != foundTransition.validToObject.isInSituation else { 
   fatalError("Transition: The toObject is already in a situation")
}

But this non matching test does not seem to be allowed. So instead using the below if statement:

if case .notInUse = foundTransition.validToObject.isInSituation {} else {
   fatalError("Transition: The toObject is already in a situation")
}

It works but feels a guard would be neater. Any ideas?

CodePudding user response:

It is impossible to negate a case statement.

You either need to use your if statement, or make the enumeration Equatable, in which case you would just drop the case keyword.

guard foundTransition.validToObject.isInSituation != .notInUse

Alternatively, you can use a guard statement that is backed by a switch or if. But you'll never get rid of them!

  • Related