Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Multiple Switch Cases

Tags:

I am making a board game where you must joins two objects. Each object has a type and there are 5 different types. For each different type combination in a merge, there will be a different effect on the game. Right now, I am working with a switch statement for each combination. So, my code would look something like this.

struct Coin {     var type = 1 }  // Each coin is of type Coin.    switch(coin1.type, coin2.type) {     case (1,1):         functionNormal()     case (1,2):         functionUncommon()     case (1,3):         functionRare()     ... } 

The objects' position doesn't change the result. A (1,2) merge will have the same effect as a (2,1) merge. Is there a less verbose way to achieve this?

like image 697
Alain Cruz Avatar asked Mar 28 '17 00:03

Alain Cruz


People also ask

Can switch case have multiple conditions Swift?

Unlike C, Swift allows multiple switch cases to consider the same value or values. In fact, the point (0, 0) could match all four of the cases in this example. However, if multiple matches are possible, the first matching case is always used.

Can switch case have multiple conditions?

A switch statement includes literal value or is expression based. A switch statement includes multiple cases that include code blocks to execute. A break keyword is used to stop the execution of case block. A switch case can be combined to execute same code block for multiple cases.

What is switch statement 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

You can pass multiple cases as comma separated like

   switch switchValue {     case .none:         return "none"     case .one, .two:         return "multiple values from case 2"     case .three, .four, .five:         return "Multiple values from case 3"     } 
like image 109
Joe Avatar answered Dec 07 '22 07:12

Joe