We all know an enum is the preferred way in listing a defined set of constants.
When the collection is fixed and not going to change ever again. There is not a problem in using the default case.
enum Season
{
case spring
case summer
case autumn
case winter
}
func isTimeForWinterVacation(season: Season) {
switch season {
case .winter:
print("Yes, let's pack.")
default:
print("No, we only go during winter period.")
}
}
isTimeForWinterVacation(season: .spring)
isTimeForWinterVacation(season: .winter)
In case you want to define a function only applicable to .winter
, there is no need to define the other seasons explicitly.
However, in case you use an enum to list a defined set of constants that is likely to be extended in the future. Please never ever use the default option. Because it is hiding the places where it is used in code. It’s much more efficient when you get help from the compiler to indicate all places that needs the extra attention.
enum BikeType
{
case regular
case racing
case mountainbike
case eBike
}
func isElectricBike(bikeType: BikeType) {
switch bikeType {
case .eBike:
print("Yes, you need to charge this one.")
default:
print("No, no charger needed.")
}
}
isElectricBike(bikeType: .regular)
isElectricBike(bikeType: .eBike)
When a new team member needs to support the .speedPedelec
bike type. He could easily add the new type to the enum. Since the extra case is covered by the default option. The compiler does not indicate anything needs to be checked and a bug could be introduced when you just reuse the existing function.
isElectricBike(bikeType: .speedPedelec)
Instead, defining the options explicitly would give the following compiler warning when adding a new bike type: Switch must be exhaustive
. And that’s exactly what you would want in this scenario. Because that would make you think about the impact on that existing functionality.
func isElectricBike(bikeType: BikeType) {
switch bikeType {
case .eBike:
print("Yes, you need to charge this one.")
case .regular, .racing, .mountainbike:
print("No, no charger needed.")
}
}
This very small tweak increases the code quality a lot.
So next time you see a switch, please remember that the default case is hiding the usage from the compiler and future developers. Use it with care!