Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a noop block for a switch case in Swift?

Tags:

swift

How do I create a noop block for a switch case in Swift? Swift forces you to have at least one executable statement under your case, including default. I tried putting an empty { } but Swift won't take that. Which means that Swift's switch case is not totally translatable between if-else and vice versa because in if-else you are allowed to have empty code inside the condition.

e.g.

switch meat {     case "pork":      print("pork is good")     case "poulet":      print("poulet is not bad")     default:      // I want to do nothing here } 
like image 272
Boon Avatar asked Jun 14 '14 21:06

Boon


People also ask

How do you skip a switch case in Swift?

You do this by writing the break statement as the entire body of the case you want to ignore."

Is Break necessary in switch case Swift?

Although break isn't required in Swift, you can use a break statement to match and ignore a particular case or to break out of a matched case before that case has completed its execution. For details, see Break in a Switch Statement. The body of each case must contain at least one executable statement.

What are the characteristics of switch in Swift?

Swift's switches must be exhaustive, so all possible values of the input must be matched. You can provide a number of cases to match against the value, and also a default case to handle any unmatched values. Another important feature of a Swift switch cases is that they do no automatically 'fallthrough'.

What is switch in Swift?

The switch statement allows us to execute a block of code among many alternatives. The syntax of the switch statement in Swift is: switch (expression) { case value1: // statements case value2: // statements ... ... default: // statements }


1 Answers

default:   break 

Apple talks about this keyword in this article. See here, too.

Although break is not required in Swift, you can still use a break statement to match and ignore a particular case, or to break out of a matched case before that case has completed its execution.

like image 176
aleclarson Avatar answered Oct 21 '22 05:10

aleclarson