Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift can a switch case statement have multiple arguments?

If I have set my cases in enum, can I call multiple of those cases in a switch statement? aka case .a, .b: return true

enum myLetters {
  case a
  case b
  case c

    var myCondition: Bool {
      switch self {
      case .a, .b: return true
      case .c: return false
      default: return false
    }
  }
}
like image 546
Kalanos Avatar asked Jun 27 '17 22:06

Kalanos


People also ask

Can we pass 2 arguments in switch case?

Use the fall-through feature of the switch statement to use a switch case with multiple arguments in JavaScript. A matched case will run until a break (or the end of the switch statement) is found.

Can a switch case have multiple values?

The switch can includes multiple cases where each case represents a particular value. Code under particular case will be executed when case value is equal to the return value of switch expression. If none of the cases match with switch expression value then the default case will be executed.

How do you use multiple cases in a switch case?

use multiple constants per case, separated by commas, and also there are no more value breaks: To yield a value from a switch expression, the break with value statement is dropped in favor of a yield statement.


2 Answers

Yes, take a look at Swift's documentation on switch statement.

In order to achieve what you want, you need to check for the current value of myLetters:

var myCondition: Bool {
    switch self {
    case .a, .b: return true
    case .c: return false
    }
}
like image 104
Mo Abdul-Hameed Avatar answered Oct 13 '22 00:10

Mo Abdul-Hameed


If you want to group cases with the same assosiated value, you can do the following:

var myCondition: Bool {
  switch self {
  case .a(let value), .b(let value): return value
  case .c(let value1, let value2): // do stuff with value1 and value 2
  }
}

Unfortunately you can't currently combine the let statements to a single one.

like image 41
danielhadar Avatar answered Oct 13 '22 00:10

danielhadar