Reputation: 54559
On Xcode 7b2 with Swift 2 code, I have following:
In a switch case the compiler returns the following warning :
Default will never be executed
The code :
switch(type) {
case .foo:
return "foo"
case .bar:
return "bar"
case .baz:
return "baz"
default:
return "?"
}
Why would there be a warning ?
Upvotes: 23
Views: 14552
Reputation: 335
I think this warning violates the open-closed principle. When you add an enum value later, the default will be missing, and you can't predict what your code will do. So you have to change also this place. Anyway, using switch() at all violates this principle.
Upvotes: 10
Reputation: 13243
This could be because type
is a enum with 3 cases and the compiler knows that the switch statement is exhaustive so you don't need a default
statement in order to handle all possible cases.
Upvotes: 4
Reputation: 54559
I just understood why :
The object I "switched" on is an enum
and my enum
only has 3 entries : .foo
, .bar
, baz
.
The compiler gets that there is no need of a default because every possibility of the enum
gets tested.
Upvotes: 61