Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine default case with other cases

Tags:

enums

swift

Given the following enum in C# and a switch/case to return the a border color of a textbox according its state for example.

enum TextboxState {
 Default,
 Error
}

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

So basically I define a real and not just by convention default state aka TextboxState.Default by adding the default: case. I just want to do this to prevent future breaking changes if new values are added to the enum.

According to the Swift book this is not possible:

“If it is not appropriate to provide a switch case for every possible value, you can define a default catch-all case to cover any values that are not addressed explicitly. This catch-all case is indicated by the keyword default, and must always appear last.”

The paragraph is quite clear about that, so I assume my pattern above does not apply to Swift or do I miss something? Is there another way to archive something like the above code?

like image 544
MBulli Avatar asked Sep 30 '14 16:09

MBulli


1 Answers

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

For example, if this is your enum (added a 3rd case to show it can handle multiple fall throughs):

enum TextboxState {
    case Default
    case Error
    case SomethingElse
}

you can format the switch statement 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, up to the default case.

like image 180
Antonio Avatar answered Oct 04 '22 03:10

Antonio