- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
来自 Swift 文档:
Typically, you use the if statement to evaluate simple conditions with only a few possible outcomes. The switch statement is better suited to more complex conditions with multiple possible permutations and is useful in situations where pattern matching can help select an appropriate code branch to execute.
我正在尝试根据我是否遇到复杂情况来决定是否应该使用 switch 或 if/else 语句。所以我的问题是,我的情况是否复杂。
这是我的例子:
var sampleVar = Measurement(value: amount, unit: UnitLength.megameters)
if(type == "inches"){
//do something
}
else if...
我要检查 5 到 15 个可能的条件,那么这是否会使它变得足够复杂以证明使用 switch 语句是合理的?还是复杂性基于条件而不是条件的数量?
最佳答案
最终测试是只写出两者并进行比较。
switch
更好当你处理一个有利于 switch
而不是 if/else 阶梯的情况时,你的代码将如下所示:
if something == 1 {
foo()
} else if something == 2 {
bar()
} else if something == 3 {
baz()
} else {
quux()
}
如你所见,所有的括号,重复关键字(else
,if
)重复运算符==
和相同的重复实例标识符 (something
) 添加了一堆毫无值(value)的杂音。与 switch
比较:
switch something {
case 1: foo()
case 2: bar()
case 3: baz()
default: quux()
}
if
/else if
/else
更好您会发现自己编写了一个开关,其中开关变量并没有真正匹配多少,而是您有一堆 where
子句来检查许多不相关的条件。比较:
switch something {
case 1: foo()
case _ where case2_1() || case2_2(): bar()
case _ where case3(): baz()
case _ where case4(): quux()
}
对比
if something == 1 || case1() { foo() }
else if case2_1() || case2_2() { bar() }
else if case3() { baz() }
else if case4() { quux() }
尽可能尝试将复杂的切换逻辑分解为对对象方法的动态调用。这允许您将每个案例的逻辑分离到一个单独的类中,所有相关的逻辑都可以在其中分组。
关于swift - 我的代码是否足够复杂以在 Swift 中使用 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56500193/
对于我的问题,我找不到更好的措辞。 在我的应用程序中的某个时刻,我设置了一些非常密集的动画。问题是,在高端设备上,动画运行流畅且赏心悦目。另一方面,我测试过的一台低端设备在制作动画时表现非常糟糕。 试
我正在修补 OTP 模块 ( yubico_pam ),并尝试访问管理员选择的控制标志(例如必需,足够, ETC)。 有什么想法吗?这是否可行(无需解析文件)? 最佳答案 无法在 API 中查询此信息
我有一些为 Linux 编写的 C 代码,依赖于套接字和 arpa/inet.h 以及 libusb.h,我想在 MinGW 下为 Windows 编译它。 (请注意,当前项目只有一个非常简单的 Ma
我是一名优秀的程序员,十分优秀!