6.控制流

2021-07-13  本文已影响0人  LucXion

控制流语句:whilerepeat-whilefor-inswitchifguardwhere

控制转移语句:continuebreakreturnfallthroughthrow

for index in stride(from: 0, to: 60, by: 5) {
    /*
     从0开始,输出0
     到60,不含60
     从0开始后第五个元素,以此类推
     */
    print(index)
}

for index in stride(from: 0, through: 60, by: 5) {
    // 闭区间,包含60
    print(index)
}

while/repeat-while

var square = 0
var diceRoll = 0
while square <= finalSquare {
    // 掷骰子
    let random = Int.random(in: 1...6)
    print(random)
    // 根据点数移动
    square += random
    
    if square < board.count {
        // 如果玩家还在棋盘上,顺着梯子爬上去或者顺着蛇滑下去
        square += board[square]
    }
}
print("Game over!")

switch

// switch 穿透
let age = 18
switch age {
case 18,19:
    print("You are 18 or 19")
    fallthrough // 允许显示穿透 fallthrough
case 16...20:
    print("You are young")
    break // 不存在隐式穿透,break可加可不加
default:
    print("cann't find info")
}

// switch 值绑定
let point = (2,2)
switch point {
case (let x,0):
    print("当前点在x轴上,x = \(x)")
case (0,var y):
    y += 1
    print("当前点在y轴上,y + 1 = \(y)")
case (let x,_):// 这个case涵盖了所有剩余分支,所以不再需要default
    print("不在x轴也不在y轴上,这里只取x = \(x)")
}

带标签的语句

可以在循环体和条件语句中嵌套循环体和条件语句来创造复杂的控制流结构

let arrA = [1,2,3,4,5]
let arrB = [6,7,8,9,10]
let arrC = [arrA,arrB]
runloop : for (index,arr) in arrC.enumerated() {
    print("index = \(index)")
    for count in arr {
        print(count)
        if count == 4 {
            break runloop // break会结束当前代码块,后面跟带标签的语句,会同时结束该标签语句
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读