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?
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.
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.
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 }
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" }
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