【Swift】基础(2)—— 控制流

1,026 阅读3分钟

if语句

Swift的if语句中,条件必须是布尔表达式,不存在与0或者nil的隐式比较,如:

var varA:Int = 100;
/* 检测布尔条件 */
if varA == 0 {
   /* 如果条件为 true 执行以下语句 */
   print("varA 小于 20");
} else {
   /* 如果条件为 false 执行以下语句 */
   print("varA 大于 20");
}

/* 下面的写法是不正确的 */
if varA {
  ...
} 

switch语句

Swift中的switch语句在执行case语句后,会直接跳出当前switch(可以看成是OC中的case全部默认地加上了break),如果需要继续往下判断,则需要添加fallthrough语句。

Swift中的switch语句比OC中的强大很多,具体请看下面几点:

1、case后面可以判断多个条件(使用","分割),如:

var index = 10

switch index {
   case 100  :
      print( "index 的值为 100")
      fallthrough
   case 10,15  :
      print( "index 的值为 10 或 15")
      fallthrough
   case 5  :
      print( "index 的值为 5")
   default :
      print( "默认 case")
}

2、可以判断字符串(爽到有没有),如:

var string1 = "AAA"

switch string1 {
   case "AAA"  :
        //...
   case "BBB","CCC"  :
      //...
   case 5  :
      //...
}

3、可以判断数字区间,如:

var salary = 100

switch salary {
    case 0..<1000:
        print("0到999")
    case 1000...10000:
        print("1000到10000")
    default:
        print("大于10000")
}

4、匹配元组

元组与数组类似,不同的是,元组中的元素可以是任意类型,使用的是圆括号。

元组也可以作为case的条件的。在case条件中,我们可以使用下划线来忽略元组中的某一项。并且我们还可以在元组中的一些项中使用区间运算符。如:

var tumple = (59,80)
switch tumple {
    case (60..<80,60..<80):
        print("都在60~80之间")
    case (60..<80,_):   
    // 可以使用下划线进行忽略掉元组中的一项
        print("第一个数在60~80之间")
    case (let first,60..<80): 
    // 还可以把不匹配的值通过参数的形式传到case后方的子语句块中
        print("第一个数是\(first),第二个数在60~80之间")
    default:
        print("没有数字在60~80之间")
}

5、Where子句 case条件中还可以跟上where子句(可以参考SQL中的where进行理解),结合上面的传递参数方式,可以达到替代if语句的效果,如:

var tumple = (59,80)
switch tumple {
    case (60..<80,60..<80):
        print("都在60~80之间")
    case (60..<80,_):   
        print("第一个数在60~80之间")
    case (let first,60..<80) where fisrt > 50: 
        print("第一个数是\(first),且大于50;第二个数在60~80之间")
    default:
        print("没有数字在60~80之间")
}

循环语句

1、for-in

与OC中的for-in循环类似,并且可以更简单的进行区间数值循环,如:

// 数值循环
for index in 1...5 {
    
}

// 遍历数组
var someInts:[Int] = [10, 20, 30]
for index in someInts {
   print( "index 的值为 \(index)")
}

2、for循环

for循环在Swift3中已废弃,就不提了

3、while循环

同C的while循环相同,只是少了条件语句的括号。

数字 0, 字符串 '0' 和 "", 空的 list(), 及未定义的变量都为 false ,其他的则都为 true。true 取反使用 ! 号或 not,取反后返回 false。

4、repeat...while循环 同C中的do...while循环,在循环执行结束时判断条件是否符合。