300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 控制语句 for while if switch

控制语句 for while if switch

时间:2021-10-31 00:33:32

相关推荐

控制语句 for while if switch

一、for…in 结构

for i in 0...4{

print(i) //使用到了变量 i

}

for _ in 0...1{ // 后期没有使用到变量,可以直接用个下划线 _ 占位就行了

print("hello")

}

二、while 结构

var i : Int = 0

while i < 5 {

print("a")

i += 1

}

//repeat…while 结构 (相当于do...while)

var j : Int = 0

repeat {

print("b")

j += 1

}while j < 2

三、if语句

//if … else if语句

var h : Int = 10

if h < 5{ //条件的判断没有小括号

print("c")

}else if h < 20 {

print("d")

}

四、switch结构

//不存在隐式的贯穿 (可以不写break)

1.switch…case 中的多个条件的使用

var sw1 : Int = 1

switch sw1 {

case 1,2,3 : print("aaa")

// break

case 5,6,7 : print("bbb")

// break

case 10,11 : print("ccc")

// break

case 15,16 : print("ddd")

// break

default:

print("eee")

}

2.switch…case 中的区间使用

var sec = 87

switch sec {

case 91...100:

print("A")

case 81...90:

print("B")

default:

print("C")

}

3.switch…case 中的元组_使用

var yuanzu = (2,2)

switch yuanzu{

case (1,1):

print("1,1")

case (2,2):

print("2,2")

case (3,3):

print("3,3")

default:

print("4,4")

}

//只判断第一个元素,第二个用下划线_表示任意

var yuanzu1 = (2,3)

switch yuanzu1{

case (_,3):

print("1,1")

case (2,_):

print("2,2")

case (3,_):

print("3,3")

default:

print("4,4")

}

4.switch…case 中的元组值绑定

var yuanzu2 = (2,3)

switch yuanzu2{

case (let x,3): //类似下滑线, 但是能获取到

print(x)

case (2,2):

print("2,2")

case (3,3):

print("3,3")

default:

print("4,4")

}

5.switch…case 中的where条件语句

var yuanzu3 = (2,3)

switch yuanzu3{

case let (x, y) where x==y :

print("相同")

default:

print("不同")

}

6.switch…case 中的fall through

var yuanzu4 = (2,2)

switch yuanzu4{

case (1,1):

print("1,1")

case (2,2):

print("2,2")

fallthrough//贯穿,继续向下执行

case (3,3):

print("3,3")

default:

break

}

总结:控制转移语句

//1.continue 告诉一个循环体立刻停止 本次 循环迭代,重新开始下次循环迭代

//2.break 会立刻结束 整个 控制流的执行

//a.当在一个循环体中使用break时,会立刻中断该循环体的执行,然后跳转到表示循环体结束的大括号(})后的第一行代码。不会再有本次循环迭代的代码被执行,也不会再有下次的循环迭代产生。

//b.当在一个switch代码块中使用break时,会立即中断该switch代码块的执行,并且跳转到表示switch代码块结束的大括号(})后的第一行代码。

//3.fallthrough 贯穿关键字不会检查它下一个将会落入执行的 case 中的匹配条件。fallthrough简单地使代码执行继续连接到下一个 case 中的执行代码

例1:

for i in 0...3{

for j in 0...3{

if j == 2{

continue //停止本次循环

}

print("i \(i) j \(j)")

}

}

例2:

//终止带 标签 的循环(给循环加个名字)

abc : for i in 0...3{

def : for j in 0...3{

if j == 2{

break abc //终止abc循环

}

print("i \(i) j \(j)")

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。