五、控制流

作者: 爱玩游戏的iOS菜鸟 | 来源:发表于2020-01-03 18:12 被阅读0次

    控制流主要关键字

    • whilerepeat-while 循环
    • ifguardswitch 基于特定的条件执行不同的代码分支
    • continuebreak 传递执行流到另一个点

    循环语句

    For-in循环
    1. 遍历数组
    let nameArr = ["lujianyong","gongxun","huangwei","dundekui","ziqiang"]
    
    for name in nameArr {
        print(name)
    }
    
    1. 遍历字典
    let numRomanDic = ["1":"one","2":"two","3":"three","4":"four"]
    for (key, value) in numRomanDic {
        print("\(key):\(value)")
    }
    
    1. 遍历数字区间
    for index in 1...20 {
        print(index)
    }
    
    //计算base的指数power的结果answer的值
    let base = 2
    let power = 10
    var answer = 1
    
    for index in 1...10 {
        answer *= base
    }
    
    print("\(base) to the power of \(power) is \(answer)")
    
    

    index 在每次遍历循环的时候自动设置,隐式地在循环的生命中声明了, 所以不需要在使用之前声明
    如果不需要index,也可以用下划线(_)代替

    1. 循环跳过标记
    let maxValue = 30
    let minuteInterval = 5
    
    //stride(from: , to: , by: ) 跳过标记  开区间
    for tickMark in stride(from: 0, to: maxValue, by: minuteInterval) {
        print(tickMark)
    }//输出:0\n    5\n   10\n  15\n   20\n  25\n
    
    //stride(from: , through: , by: ) 跳过标记  闭区间
    for tickMark in stride(from: 0, through: 30, by: minuteInterval) {
        print(tickMark)
    }//输出:0\n    5\n   10\n  15\n   20\n  25\n  30\n
    
    while循环
    • 循环执行一个语句直到条件变成false结束(主要用于当循环次数不确定时):
    • while在每次循环开始时计算条件; repeat-while在每次循环结束时计算条件
      爬梯游戏帮助我们更好地理解
    //爬梯子游戏
    let finalSquare = 30
    var board = Array.init(repeating: 0, count: finalSquare+1)
    
    board[03] = +08;board[06] = +11;board[09] = +09;board[10] = +03;board[11] = -10;
    board[14] = -10;board[19] = -11;board[22] = -02;board[24] = -08;board[28] = -08;
    
    var square = 0
    var dicRoll = 0
    
    while square < finalSquare {
        //roll the dice 掷骰子模拟
        dicRoll += 1
        if dicRoll == 7 {
            dicRoll = 1
        }
        //move by the rolled amout 移动至指定格子
        square += dicRoll
        
        //判断是否超出越界 以及是否有梯子
        if square<board.count {
            square += board[square];
        }
        print(square,dicRoll)
    }
    
    print("game over")
    
    repeat{
        //move up or dowm for a snake or ladder 当前格子的移动情况
        square += board[square]
        
        //掷骰子
        dicRoll += 1
        if dicRoll == 7 {
            dicRoll = 1
        }
        square += dicRoll
        
        print(square,dicRoll)
    }while square < finalSquare
    
    print("game over")
    
    let arr = [10, -10, 20, -3, 0, 65, 34, -12]
    
    for num in arr where num > 0{
        print(num)//输出:10 20 65 34
    }
    

    While循环也可以添加where 过滤作用,不是循环结束的条件

    条件语句

    1. if 和OC一样
    2. Switch..case..default
    //常规匹配
    let char :Character = "a"
    
    switch char {
    case "a","A":
        print("The letter A")
    case "b","B",
         "c","C":
        print("The letter B/C")
    default:
        print("The Another letter")
    }
    
    //不包含default 但是包含所有情况
    enum Answer {
        case right
        case wrong
    }
    let answer = Answer.wrong
    switch answer {
        case Answer.right:
            print("Answer.right")
        case .wrong://由于已确定answer类型,可以省略Answer
            print("Answer.wrong")
    }
    
    //区间匹配
    let approximateCount = 151
    let countedThings = "heros"
    var naturalCount : String
    
    switch approximateCount {
        case 0:
            naturalCount = "no"
        case 1..<5:
            naturalCount = "a few"
        case 5..<12:
            naturalCount = "several"
        case 12..<100:
            naturalCount = "dozens of"
        case 100..<1000:
            naturalCount = "hundreds of"
        default:
            naturalCount = "many"
    }
    print("There are \(naturalCount) \(countedThings)")//There are hundreds of heros
    
    //元组匹配
    //每个元组中的元素都可以与不同的值或者区间进行匹配
    //使用下划线(_)来表明匹配所有可能的值
    
    //决定坐标是否在原点(0,0);在X轴;在Y轴;在4*4并以原点为中心的方格中;或者在方格外面
    
    let somePoint = (-3,2)
    
    switch somePoint {
        case (0,0):
            print("(0,0) is at the origin")
        case (_,0):
            print("(\(somePoint.0),0) is on the X-axis")
        case (0,_):
            print("(0,\(somePoint.1)) is on the Y-axis")
        case (-2...2,-2...2):
            print("(\(somePoint.0),\(somePoint.1)) is on the box")
        default:
            print("(\(somePoint.0),\(somePoint.1)) is outside of the box")
    }
    
    //在case的情况的函数体里“绑定”到临时的常量或者变量
    
    //决定坐标是否在X轴;在Y轴;或者在其他地方
    
    let somePoint = (-3,2)
    
    switch somePoint {
        case (let x,0):
            print("on the X-axis with an x value of \(x)")
        case (0,let y):
            print("on the Y-axis with an y value of \(y)")
        case let (x,y):
            print("somewhere else at (\(x),\(y))")
    }
    
    //决定坐标是否在x == y;还是在x== -y;或者在其他地方
    
    let somePoint = (-1,9)
    //Switch 情况可以使用 where 分句来检查额外的情况
    switch somePoint {
        case let (x,y) where x == y:
            print("(\(x),\(y)) is one the line x == y")
        case let (x,y) where x == -y:
            print("(\(x),\(y)) is one the line x == -y")
        case let (x,y):
            print("(\(x),\(y)) is just some arbitrary point")
    }
    

    【注意】与OC不同的点:
    if后面的条件省略小括号,大括号不可省略 if只能是bool类型
    没有隐式贯穿 不再需要显式的break语句 case后不能写大括号({})! 如果需要贯穿 需要使用fallthrough关键字
    Switch需要保证能处理所有情况,且每个情况都必须包含可执行语句 不能同时匹配多个分支 (但可以将多个情况的写在一个case中)
    Switch也支持CharacterString区间元组匹配
    Switch 情况可以使用 where 分句来检查额外的情况

    控制转移语句

    • continue break fallthrough(循环控制)
    • return(函数)
    • throw(抛出函数传递错误)
    • fallthrough (贯穿case)
    • guard (提前退出)
    //给循环语句打标签
    
    let finalSquare = 30
    var board = Array.init(repeating: 0, count: finalSquare+1)
    
    board[03] = +08;board[06] = +11;board[09] = +09;board[10] = +03;board[11] = -10;
    board[14] = -10;board[19] = -11;board[22] = -02;board[24] = -08;board[28] = -08;
    
    var square = 0
    var dicRoll = 0
    
    gameLoop: while square < finalSquare {
        //roll the dice 掷骰子模拟
        dicRoll += 1
        if dicRoll == 7 {
            dicRoll = 1
        }
        
        //move by the rolled amout 移动至指定格子
        switch square + dicRoll {
        case finalSquare:
            break gameLoop
        case let newSquare where newSquare > finalSquare:
            square += 1//防止死循环 只要骰子超出则只跳一格
            continue gameLoop
        default:
            square += dicRoll
            square += board[square]
        }
    
        print(square,dicRoll)
    }
    
    print("game over")
    
    func greet(person:[String:String]){
        guard let name = person["name"] else {
            return
        }
        
        print("hello \(name)")
        
        guard let location = person["location"] else {
            print("I hope the weather id nice near you")
            return
        }
        
        print("I hope the weather id nice in \(location)")
    }
    
    greet(person: [:])
    greet(person: ["name":"john"])
    greet(person: ["name":"mike","location":"Beijing"])
    /*
    Who are you?
    hello john
    I hope the weather id nice near you
    hello mike
    I hope the weather id nice in Beijing
    */
    

    【注意】Swift去除了 ++-- 运算符

    Swift学习日记5.0

    相关文章

      网友评论

        本文标题:五、控制流

        本文链接:https://www.haomeiwen.com/subject/ifttactx.html