美文网首页swiftSwift
Swift - Control Flow

Swift - Control Flow

作者: ienos | 来源:发表于2018-06-08 11:39 被阅读22次

    For-In Loops

    for index in 1...5 {
        // index 是常量,已隐式定义 let index
        print("\(index)")
    }
    
    for _ in 1...5 {
        // _ 忽略
    }
    

    忽略一些值 stride

    let minutes = 60
    let minuteInterval  = 5
    for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
        // 0, 5, 10, 15, 20 .. 50, 55
    }
    

    While Loops - 适用于不清楚循环次数

    while:先执行条件再执行循环内容
    repeat-while:先执行循环内容再执行条件

    IF

    Switch

    • 不需要加 break,执行完语句直接跳出,不会进入下一个 case 语句(没有隐式穿透)
    • 必须至少能够匹配其中一个语句
    • 但是仍然可以使用 break 用于提前跳出
    • case 中至少有一个执行语句,如果需要忽略可以用 break 代替
    • 在一个 case 中可以匹配多值组合,用 "," 分割值 case "a", "b" :
    • 可以分行显示
      case "a",
      "b" :
    • 间距匹配 case 1..4 : match between 1 and 4
    let someCharacter: Character = "z"
    switch someCharacter {
    case "a":
        print("The first letter of the alphabet")
    case "b", "c":
        print("b OR c")
    default:
        print("Some other character")
    }
    

    元祖匹配多值
    用 "_" 匹配任意值,允许多个 switch case 匹配同一个值,但是会按照执行顺序优先匹配

    let somePoint = (1, 1)
    switch somePoint {
    case (0, 0):
        print("\(somePoint) is at the origin")
    case (_, 0):
        print("\(somePoint) is at the x-axis")
    case (0, _):
        print("\(somePoint) is at the y-axis")
    case (-2...2, -2...2):
        print("\(somePoint) is at the box")
    default:
        print("\(somePoint) is outside of the box")
    }
    

    值绑定

    let anotherPoint = (2, 0)
    switch anotherPoint {
    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 a y value of \(y)")
    case let(x, y):
        print("somewhere else at (\(x), \(y)")
    // let(x, y) 包含所有情况,不需要 default
    }
    

    where 添加附加条件

    let yetAnotherPoint = (1, -1)
    switch yetAnotherPoint {
    case let (x, y) where x == y:
        print("(\(x), \(y) is on the line x == y")
    case let (x, y) where x == -y:
        print("(\(x), \(y) is on the line x == -y")
    case let (x, y):
        print("(\(x), \(y) is just some arbitrary point")
    }
    

    case 中组合包含值绑定
    所有组合情况的所有 patterns 必须包含相同值绑定集,每一个值绑定必须从组合情况的所有类型中获取一个相同类型的值。才能保证,无论匹配哪一个组合case,代码能够始终访问绑定的值 ,值始终有相同的类型。

    let stillAnotherPoint = (9, 0)
    switch stillAnotherPoint {
    case (let distance, 0), (0, let distance):
        print("On an axis, \(distance) from the origin")
    default:
        print("Not on an axis")
    }
    

    控制语句转换

    • continue 结束本轮执行,开始下一轮 loop
    • break 跳出完整的控制流语句 switch OR loop
    • fallthrough 穿透,区别于 C 的 switch 需要 fallthrough 才能执行下一个 case
    • return
    • throw

    给语句加标签

    适用于循环和条件嵌套语句

    let finalSquare = 25
    var square = 0
    var diceRoll = 0
    var board = [Int](repeating: 0, count: finalSquare + 1)
    
    gameLoop : while square != finalSquare { // while 标签 gameLoop
        diceRoll += 1
        if diceRoll == 7 {
            diceRoll = 1
        }
        switch square + diceRoll {
        case finalSquare:
            break gameLoop // 如果这里使用 break 只会跳出 switch 语句
        case let newSquare where newSquare > finalSquare:
            continue gameLoop
        default:
            square += diceRoll
            square += board[square]
        }
    }
    

    提前结束 guard

    func greet(person: [String: String]) {
        // 如果条件为 YES,可选绑定的值可以为后面的代码使用
        guard let name = person["name"] else {
            return // 提前结束
            // 使用控制转换语句 return, break, continue 或者 thorw
            // 也可以使用不需要 return 的 fatalError
        }
        
        print("Hello \(name)")
        
        guard let location = person["location"] else {
            print("I hope the weather is nice near you.")
            return
        }
        
        print("I hope the weather is nice in \(location).")
    }
    

    检查 API 有效性

    • swift 会在编译的时候报出 API 无效的错误
    • 使用 if OR guard
    if #available(iOS 10, *) { // 可以再添加其他平台
        // eg if #available(iOS 10, macOS 10.12, *)
        
    } else {
        
    }
    

    相关文章

      网友评论

        本文标题:Swift - Control Flow

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