23

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 ?

3 Answers 3

61

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you mark your answer as correct, please so that everyone can see that your question was answered.
perfect solution.
10

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.

1 Comment

As soon as you add another value you're code will stop compiling. The compiler throws an error at each switch statement where the cases are being considered. This comment is a bit late, but hopefully still useful.
4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.