控制语句

if语句

var m:Int = 1;

m = 3;

if m>2 {

print("m大于2");

} else {

print("\(m)");

}

switch

swift不需要加break跳出

var name:String = "小明";

name = "系哦啊";

switch name {

case "小明":

print("牛逼");

default:

print("二逼");

}

区间匹配

let age:Int = 10;

switch age {

case 0...10:

print("萝莉");

default:

print("未知");

}

元祖匹配

let point = (2,0);

switch point {

case (0,0):

print("点在坐标原点");

case (_,0):

print("点在x轴上");

case (0,_):

print("点在y轴上");

case (-3...3, -3...3):

print("坐标在长宽为6的正方形内")

default:

print("点");

}

case中还可以使用where关键字来做额外的判断条件

//var声明

var n:Int = 6;

switch n {

case 0...10 where n==6:

print("n====6");

case 0...10:

print("11");

default:

print("");

}

for循环

//已弃用

//for var i=1; i<100; i++ {

//  print("\(i)")

//}
for i in 10..<20 {

print("i============\(i)");

}
let GPLArr = [1,2,3,4];

for a in GPLArr {

print("GPLArr======\(a)");

}

forEach

(1...10).forEach {

print($0)

}

while

//        格式:while 布尔值 {}

//        说明:只有当while后面的布尔值为false,才停止while语句,否则一直执行while语句

var h = 0 //只有满足条件(i<5)才跳出while语句

while (h<5) {

print("h=\(h)")

h += 1

}


你可能感兴趣的:(控制语句)