2

In the following code sample, I don't understand why "Value 7" gets printed instead of "Default". Case 7, i.e. x=7 is not met because x=6, so why does "Value 7" get printed instead of being skipped and the execution falling through to default?

let x = 6   switch x {   case 0...5: println("0 through 5")   case 6: fallthrough   case 7: println("Value 7")   default: println("Default") } 
3
  • 1
    Possible duplicate of Swift: Switch statement fallthrough behavior Commented Feb 21, 2017 at 19:04
  • 1
    Also see the fallthrough section of the language guide – "The fallthrough keyword does not check the case conditions for the switch case that it causes execution to fall into. The fallthrough keyword simply causes code execution to move directly to the statements inside the next case (or default case) block, as in C’s standard switch statement behavior." Commented Feb 21, 2017 at 19:05
  • Thank you, Hamish. Commented Feb 21, 2017 at 20:04

1 Answer 1

5

When x = 6 the switch statements finds the case for 6 then it 'falls through' to the next case not the default one. If you want the case for 6 to execute the code under default remove that case as it does nothing. If you plan to add some code to the case for 6 then make it the last one before default so it falls through to the place you want.

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

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.