3

I have a switch statement that shows different banners according to a type variable.

switch type { case HPBannerType.NetworkUnavailableBanner: break case HPBannerType.LocationServiceUnavailableBanner: break case HPBannerType.LocationServiceDisabledBanner: break default: break } 

The type variable is of type HPBannerType which is an enum:

enum HPBannerType: String{ case NetworkUnavailableBanner = "HPNetworkUnavailableBanner" case LocationServiceUnavailableBanner = "HPLocationServiceUnavailableBanner" case LocationServiceDisabledBanner = "HPLocationServiceDisabledBanner" } 

There isn't quite a default type out of 3 types. When I write the switch statement, I have to list all of the cases for clearer understanding. This leaves the ending "default" state an useless state and shows the warning.

Default will never be executed 

How could I silence this warning?

EDIT:

@Eric D. has absolute the right solution. But the reason I posted this is because

at first, I did not use the shorthand form .XXX but the complete form HPBannerType.XXX, when I remove the default tag, XCode gave me 200 errors!

So to correct this problem, you HAVE to use shorthand form to allow XCode to recognize if its exhaustive switch statement! Or you will get error. You can try the following:

switch type { case HPBannerType.NetworkUnavailableBanner: break case HPBannerType.LocationServiceUnavailableBanner: break case HPBannerType.LocationServiceDisabledBanner: break } 

This will raise error!

1
  • 2
    You can even remove the type in the case lines within the switch expression: case .NetworkUnavailableBanner: break, the compiler knows the type. Commented Dec 5, 2015 at 22:07

1 Answer 1

10

You don't need to include default when switching over your enum because the compiler knows the switch is exhaustive (you've covered all cases):

switch type { case HPBannerType.NetworkUnavailableBanner: break case HPBannerType.LocationServiceUnavailableBanner: break case HPBannerType.LocationServiceDisabledBanner: break } 

As @vadian commented, you can also use a shorter syntax, because the compiler already knows that type is an enum of type HPBannerType:

switch type { case .NetworkUnavailableBanner: break case .LocationServiceUnavailableBanner: break case .LocationServiceDisabledBanner: break } 
Sign up to request clarification or add additional context in comments.

3 Comments

There is only one problem! I will post it in my new edit.
In short, you HAVE to use shorthand form to make compiler know if your switch is exhaustive
@user3441734 No problem for me either. OP must have had a typo somewhere.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.