简体   繁体   中英

Swift 3 associated value enum comparison syntax with OR (`||`)

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 ChatItemType s 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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM