Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Switch case: Default will never be executed warning

Tags:

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 ?

like image 643
Matthieu Riegler Avatar asked Jul 05 '15 23:07

Matthieu Riegler


People also ask

Does default in switch always executed?

The default statement is executed if no case constant-expression value is equal to the value of expression . If there's no default statement, and no case match is found, none of the statements in the switch body get executed.

Can a switch statement not have a default?

A default clause; if provided, this clause is executed if the value of expression doesn't match any of the case clauses. A switch statement can only have one default clause.

Is default case optional in switch?

A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Can we use default first in switch case?

The position of default doesn't matter, it is still executed if no match found. // The default block is placed above other cases. 5) The statements written above cases are never executed After the switch statement, the control transfers to the matching case, the statements written before case are not executed.


1 Answers

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.

like image 61
Matthieu Riegler Avatar answered Oct 13 '22 09:10

Matthieu Riegler