首页 > 解决方案 > 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 语句?

标签: iosswiftswitch-statement

解决方案


它应该写成:

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有实力。使用最适合您需要的代码/逻辑的。或者,在这种情况下,不要使用任何一种。


推荐阅读