if案例的补充 [英] complementery of an if case

查看:147
本文介绍了if案例的补充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你会怎么写这个:

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

我知道我可以使用后卫

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

但我不认为它是干净的,因为它实际上不是一个功能无法完成的情况。此外, guard 希望我从该函数返回。

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.

还有其他选择吗?

推荐答案

你不能否定一个模式(据我所知),你的第一个解决方案
使用 if / else 对我来说很好,代码的意图显然是
可见。

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.

一个switch语句可以替代:

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
    // ...
}

关于你的评论


此外,警卫希望我从函数。

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.

这篇关于if案例的补充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆