Reputation: 4363
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!
Upvotes: 3
Views: 3498
Reputation: 70098
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
}
Upvotes: 10