complementery of an if case

前端 未结 1 543
北海茫月
北海茫月 2020-12-21 07:52

How would you write this:

if case .SomeEnum(3) = enumType where myInt == 3 {
   //I don\'t need this case
} else {
   //This is the case I need
}


        
相关标签:
1条回答
  • 2020-12-21 08:39

    You cannot negate a pattern (as far as I know), and your first solution using if/else looks fine to me, the intention of the code is clearly visible.

    A switch statement would be an alternative:

    switch enumType {
    case .SomeEnum(3) where myInt == 3:
        break  // I don't need this case
    default:
        // This is the case I need
        // ...
    }
    

    With regard to your remark

    Also, guard expects me to return from the function.

    that is not entirely true. You are expected to leave the current scope. So this would compile and work as expected:

    repeat {
        guard case .SomeEnum(3) = enumType where myInt == 3 else {
            // This is the case I need
            // ...
            break
        }
    } while false
    

    but I would not consider that a better solution.

    0 讨论(0)
提交回复
热议问题