Combine the default case with other cases

Given the following enumeration in C # and the / case switch, to return the border color of the text field according to its state, for example.

enum TextboxState { Default, Error } switch(foo) { default: case TextboxState.Default: return Color.Black; case TextboxState.Error: return Color.Red; } 

Thus, basically I define the real, not just the default default state of aka TextboxState.Default , adding the case default: I just want to do this to prevent future changes if new values ​​are added to the enumeration.

According to the Swift book, this is not possible:

"If it is not practical to provide a switching case for all possible values, you can define a default blocking case for all values ​​that are not considered explicitly. In this case, the entire default keyword should always be displayed last ."

Is it clear in this paragraph that I assume that my template above is not Swift or am I missing something? Is there any other way to archive something like the above code?

+7
enums swift
source share
2 answers

You can use fallthrough to do this by moving the general behavior in the default case and using fallthrough in all cases for which you want the general behavior to occur.

For example, if this is your enumeration (a third case has been added to show that it can handle several failures):

 enum TextboxState { case Default case Error case SomethingElse } 

you can format the switch as follows:

 switch(foo) { case TextboxState.Error: return UIColor.redColor() case TextboxState.Default: fallthrough case TextboxState.SomethingElse: fallthrough default: return UIColor.blackColor() } 

Each fallthrough moves the execution point to the next case, right up to the default case.

+11
source share

Remove the default: line from switch . Even if you ever add extra cases to your list, the Swift compiler will complain if you don't add the appropriate cases to every switch that uses an enumeration. And FYI, you do not need to specify TextboxState. before the case values ​​in switch , because the compiler knows that foo is a TextboxState . Final code:

 switch(foo) { case .Default: return Color.Black; case .Error: return Color.Red; } 

although for consistency I would put a .Error case before .Default .

+1
source share

All Articles