iOS Swift-控制流(The Swift Programming Language)

时间:2023-03-10 01:55:15
iOS Swift-控制流(The Swift Programming Language)

iOS Swift-控制流(The Swift Programming Language)


for-in

在Swift中for循环我们可以省略传统oc笨拙的条件和循环变量的括号,但是语句体的大括号使我们必须要写的,拿一个遍历数组的例子来介绍:

//遍历数组中的元素
let listArray = [1,2,3,4,5,6,7,8,9];
for number in listArray {
print(number)
}

如果我们想让循环体循环10次我们该怎么去做呢???

//这是一个很不错的方法
for number in 0 ..< 10 {
print(number)
}
//0 ...10表示的是取:0,1,2,3,4,5,6,7,8,9,10

if

在Swift中if的条件必须是一个布尔表达式,而不会隐式的与0作比较,也就意味着下面的代码会报错.

let temp = 10;
if temp {
print("handsome")
}

因此我们要更规范的使用if,例如下面的使用方法.

let temp = 10;
if temp < 100 {
print("handsome")
}

除此之外三目运算Swift也是支持的.

let  str : String = num1 > num2 ? "num1 > num2" : "num1 < num2"
print(str)

switch

Swift中的switch将不仅仅是证书以及测试的相等,还支持任意类型的数据以及各种比较操作.除此之外case匹配后并不需要break,以及删除default将会报错.

let string = "handsome"
switch string {
case "handsome":
print("handsome")
default:
print("no handsome")
}

while

在Swift中While与OC中的While是没有很大的区别的.

while:

while 1 < 2 {
print("handsome")
}

repeat~while:

repeat {
print("handsome")
}while 1 < 2