Skip to main content
[Edit removed during grace period]
Link
Leo Dabus
  • 237.5k
  • 61
  • 512
  • 624
Source Link
Mehul Parmar
  • 3.7k
  • 3
  • 28
  • 42

Using @unknown default in swift 5 enum : How to suppress "Default will never be executed" warning?

Let's say I have an existing code as follows:

enum SomeEnumCases { case existing case alreadyExisting } func doSomething(withEnums enumCase: SomeEnumCases) { switch enumCase { case .existing: print("This case was already existing") case .alreadyExisting: print("This case was already existing too...") } } 

Now, if I were to add a new case the the enum, the function above would show a compile error saying the switch case must be exhaustive, and I would be FORCED to handle the new missing case. I would add a third case in the switch statement, or add a default statement.

Now, I order to handle such unforeseen enum cases, I would like to add an @unknown default case to the existing function above. The only problem is, now it would give me a warning saying Default will never be executed.

So the question is, how do I future-proof my enum such that I can:

  1. Exhaustively handle all current enum cases, AND
  2. Have a default handling mechanism for the future unknown case, AND
  3. See a warning only when newer cases are added and these cases must be handled by the default case.

That means, the following code SHOULD NOT give warnings:

enum SomeEnumCases { case existing case alreadyExisting } func doSomething(withEnums enumCase: SomeEnumCases) { switch enumCase { case .existing: print("This case was already existing") case .alreadyExisting: print("This case was already existing too...") @unknown default: // <-- warning: Default will never be executed: should be suppressed print("Alright, this is something new and exciting !!") } } 

but the following code SHOULD give a warning:

enum SomeEnumCases { case existing case alreadyExisting case new } func doSomething(withEnums enumCase: SomeEnumCases) { switch enumCase { // <-- warning: Switch must be exhaustive: This should stay. case .existing: print("This case was already existing") case .alreadyExisting: print("This case was already existing too...") @unknown default: print("Alright, this is something new and exciting !!") } } 

Is that possible through @unknown or otherwise ?