ios - swift:如何在 switch case 语句中替换 if else
问题描述
我有这张if else
支票:
var aItem: CGFloat = 0
if item == 0 {
aItem = 457
} else if item == 1 {
aItem = 576
} else if item == 2 {
aItem = 758
}
print(aItem)
switch
我想用case 语句替换这段代码。怎么做?
我试过:
var aItem: CGFloat = 0
switch item {
case _ where item == 0:
aItem = 457
case _ where item == 1:
aItem = 576
case _ where item == 2:
aItem = 758
default:
print("this is impossible")
}
它是有效的,但它是最好的解决方案吗?也许可以以某种方式简化这段代码?
什么更好用?if else 或 switch case 语句?
解决方案
它应该写成:
let aItem: CGFloat
switch item {
case 0:
aItem = 457
case 1:
aItem = 576
case 2:
aItem = 758
default:
aItem = 0
print("this is impossible")
}
print(aItem)
如果事实是您item
只能是 0、1 或 2,我会这样做:
let anItem: CGFloat = [457, 576, 758][item]
if else
在这种情况下,使用or之间几乎没有区别switch
。选择你最喜欢的。if
并且switch
有实力。使用最适合您需要的代码/逻辑的。或者,在这种情况下,不要使用任何一种。
推荐阅读
- javascript - Onclick 在第三方表单 iframe 中填写表单字段
- networking - Netplan 错误:无法绑定到端口 2893,地址已在使用中
- html - 由于未知原因,圆锥梯度 css 在 React 中不起作用
- mysql - MySQL 左/右/外连接
- python - 使用 Django 的 ORM 聚合 OneToMany 关系中不同日期的数量
- javascript - mongodb函数currentOp()的返回记录在哪里?
- sql - 如何将选择查询的结果放入 postgresql 中的函数
- php - 打开引导模式后,我的 php 变量被重置
- c++ - 如何基于循环迭代器选择函数
- android - Android 导航组件重新创建底部导航片段