1

I've got an enum with an associated value, ChatItemType:

enum ChatItemType {
  case message(ChatBubbleType)
  case log
  case timestamp
}

I'm doing a comparison like this in an if-statement:

if case .log = givenType {
  return true
} else if case .timestamp = givenType {
  return true
} else {
  return false
}

It obviously makes sense to combine the first and second statement as they both return true. But using || the way I'd expect it to be used seems to give me a syntax error:

if case .log = givenType || case .timestamp = givenType

I'm aware that I could just check for the .message type instead and else return true, but more ChatItemTypes are likely to be added in the future, so I'd like to still know how to properly combine comparisons.

I'm finding it hard to find the answer to this online mainly because I'm not sure of the right terminology to refer to these concepts. Any guidance there appreciated, too.

Elise
  • 5,086
  • 4
  • 36
  • 51
  • 1
    The easiest solutions are `if [.timestamp, .log].contains(givenType)` or `if givenType == .log || givenType == .timestamp` – Toldy May 03 '17 at 11:36
  • 1
    @Toldy: That won't compile for enums with associated values, for the same reason as mentioned here: http://stackoverflow.com/questions/43716891/confused-with-swift-enum-syntax?noredirect=1#comment74477326_43716891) – Martin R May 03 '17 at 11:38

1 Answers1

7

You can not compare against multiple patterns in a if statement (as far as I know), but you can do so in a switch statement:

switch givenType {
case .log, .timestamp:
    return true
case .message: 
    return false
}

(Explicitly enumerating all cases instead of using a default case ensures that you won't forget to update the function if another case is added to the type later.)

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks. For some reason I remembered that switch statements have a catch to them in case of associated value enums, but this seems to work fine! – Elise May 03 '17 at 11:37