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 ?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With