Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

ios - complementery of an if case

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
}

I know I could use guard:

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

but I don't think it is clean, since it is not really a case in which the function is not able to finish. Also, guard expects me to return from the function.

Any other alternatives?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...