如何在swift中正确编写条件语句?

时间:2015-05-29 11:48:50

标签: swift conditional-statements

我是swift的新手,基于ios开发人员库我找到了这个条件语句代码:

if *condition 1* {
    *statements to execute if condition 1 is true*
} else if *condition 2* {
    *statements to execute if condition 2 is true*
} else {
    *statements to execute if both conditions are false*
} 

但我想要的是这样的东西:

 if *condition 1* {
    *statements to execute if condition 1 is true*
} else {
    *statements to execute if condition 1 is false*
} 
 if *condition 2* {
    *statements to execute if condition 2 is true*
} else {
    *statements to execute if condition 2 is false*
} 
 if *condition 3* {
    *statements to execute if condition 3 is true*
} else {
    *statements to execute if condition 3 is false*
} 
 if *condition 4* {
    *statements to execute if condition 4 is true*
} else {
    *statements to execute if condition 4 is false*
} 

是否有任何解决方案可以做到正确,如果我的问题听起来很愚蠢,我很抱歉?

1 个答案:

答案 0 :(得分:0)

<强>更新

我接受了我的建议。我误解了这个问题。没有看到每个条件都有一个else语句。我的坏。

原始答案

这取决于条件复杂性,但通常可以使用switch语句来检查多个条件。

来自Apple的docs

  

Swift提供了两种向代码添加条件分支的方法,   称为if语句和switch语句。通常,您使用   用于评估简单条件的if语句只有少数几个   可能的结果。 switch语句更适合更多   具有多种可能排列的复杂条件,并且是有用的   在模式匹配可以帮助选择合适的情况下   代码分支执行。

     

switch语句会考虑一个值并将其与几个值进行比较   可能的匹配模式。然后它执行适当的块   代码,基于第一个匹配成功的模式。一个开关   statement提供了if语句的替代方法   多个潜在的状态。

     

最简单的形式是,switch语句将值与1进行比较   或更多相同类型的值:

switch some value to consider {
case value1:
    //respond to value 1
case value2,
value3:
    //respond to value 2 or 3
default:
    //otherwise, do something else
}