美文网首页
Swift:控制流

Swift:控制流

作者: 伯wen | 来源:发表于2018-07-08 23:01 被阅读5次

    中文文档

    一、For-In 循环

    • 你可以使用 for-in 循环来遍历一个集合中的所有元素

    • 使用 for-in 遍历一个数组所有元素:

    let names = ["Anna", "Alex", "Brian", "Jack"]
    for name in names {
        print("Hello, \(name)!")
    }
    // Hello, Anna!
    // Hello, Alex!
    // Hello, Brian!
    // Hello, Jack!
    
    • 可以通过遍历一个字典来访问它的键值对
    let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
    for (animalName, legCount) in numberOfLegs {
        print("\(animalName)s have \(legCount) legs")
    }
    // ants have 6 legs
    // spiders have 8 legs
    // cats have 4 legs
    
    • for-in 循环还可以使用数字范围
    for index in 1...5 {
        print("\(index) times 5 is \(index * 5)")
    }
    // 1 times 5 is 5
    // 2 times 5 is 10
    // 3 times 5 is 15
    // 4 times 5 is 20
    // 5 times 5 is 25
    
    • 如果你不需要区间序列内每一项的值,你可以使用下划线(_)替代变量名来忽略这个值:
    let base = 3
    let power = 10
    var answer = 1
    for _ in 1...power {
        answer *= base
    }
    print("\(base) to the power of \(power) is \(answer)")
    // 输出 "3 to the power of 10 is 59049"
    
    • stride(from:to:by:)函数可以设置每次遍历的步长, 遍历区间是左闭右开区间
    let total = 60
    let length = 5;
    for index in stride(from: 0, to: total, by: length) {
        print(index, terminator: " ")
    }
    // 打印: 0 5 10 15 20 25 30 35 40 45 50 55 
    
    • stride(from:through:by:)闭区间中以步长遍历
    let total = 60
    let length = 5;
    for index in stride(from: 0, through: total, by: length) {
        print(index, terminator: " ")
    }
    // 打印: 0 5 10 15 20 25 30 35 40 45 50 55 60 
    

    二、While 循环

    Swift 提供两种 while 循环形式:

    • while 循环,每次在循环开始时计算条件是否符合;
    • repeat-while 循环,每次在循环结束时计算条件是否符合。
    1、while
    • while 循环从计算一个条件开始。如果条件为 true,会重复运行一段语句,直到条件变为 false。
    • 下面是 while 循环的一般格式:
    while condition {
        statements
    }
    
    2、Repeat-While
    • 下面是 repeat-while 循环的一般格式:
    repeat {
        statements
    } while condition
    

    三、条件语句

    • Swift 提供两种类型的条件语句:if 语句和 switch 语句。通常,当条件较为简单且可能的情况很少时,使用 if 语句。而 switch 语句更适用于条件较复杂、有更多排列组合的时候。并且 switch 在需要用到模式匹配(pattern-matching)的情况下会更有用。
    1、If
    • if 语句最简单的形式就是只包含一个条件,只有该条件为 true 时,才执行相关代码:
    var temperatureInFahrenheit = 30
    if temperatureInFahrenheit <= 32 {
        print("It's very cold. Consider wearing a scarf.")
    }
    // 输出 "It's very cold. Consider wearing a scarf."
    
    • 当然,if 语句允许二选一执行,叫做 else 从句。也就是当条件为 false时,执行 else 语句:
    temperatureInFahrenheit = 40
    if temperatureInFahrenheit <= 32 {
        print("It's very cold. Consider wearing a scarf.")
    } else {
        print("It's not that cold. Wear a t-shirt.")
    }
    // 输出 "It's not that cold. Wear a t-shirt."
    
    • 你可以把多个 if 语句链接在一起,来实现更多分支:
    temperatureInFahrenheit = 90
    if temperatureInFahrenheit <= 32 {
        print("It's very cold. Consider wearing a scarf.")
    } else if temperatureInFahrenheit >= 86 {
        print("It's really warm. Don't forget to wear sunscreen.")
    } else {
        print("It's not that cold. Wear a t-shirt.")
    }
    // 输出 "It's really warm. Don't forget to wear sunscreen."
    
    • 当不需要完整判断情况的时候,最后的 else 语句是可选的:
    temperatureInFahrenheit = 72
    if temperatureInFahrenheit <= 32 {
        print("It's very cold. Consider wearing a scarf.")
    } else if temperatureInFahrenheit >= 86 {
        print("It's really warm. Don't forget to wear sunscreen.")
    }
    
    2、Switch
    • switch 语句会尝试把某个值与若干个模式(pattern)进行匹配。根据第一个匹配成功的模式,switch 语句会执行对应的代码。当有可能的情况较多时,通常用 switch 语句替换 if 语句。
    switch some value to consider {
    case value 1:
        respond to value 1
    case value 2, value 3:
        respond to value 2 or 3
    default:
        otherwise, do something else
    }
    
    • 与 if 语句类似,每一个 case 都是代码执行的一条分支。switch 语句会决定哪一条分支应该被执行,这个流程被称作根据给定的值切换
    • 在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止 switch 语句,而不会继续执行下一个 case 分支。

    • 这也就是说,不需要在 case 分支中显式地使用 break 语句。

    • 这使得 switch 语句更安全、更易用,也避免了因忘记写 break 语句而产生的错误。

    注意
    虽然在 Swift 中 break 不是必须的,但你依然可以在 case 分支中的代码执行完毕前使用 break 跳出

    • 每一个 case 分支都必须包含至少一条语句。像下面这样书写代码是无效的,因为第一个 case 分支是空的:
    let anotherCharacter: Character = "a"
    switch anotherCharacter {
    case "a": // 无效,这个分支下面没有语句
    case "A":
        print("The letter A")
    default:
        print("Not the letter A")
    }
    // 这段代码会报编译错误
    
    • case 分支的模式也可以是一个值的区间
    let approximateCount = 62
    let countedThings = "moons orbiting Saturn"
    let 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 dozens of moons orbiting Saturn."
    
    • 我们可以使用元组在同一个 switch 语句中测试多个值。元组中的元素可以是值,也可以是区间。另外,使用下划线(_)来匹配所有可能的值。
    let somePoint = (1, 1)
    switch somePoint {
    case (0, 0):
        print("\(somePoint) is at the origin")
    case (_, 0):
        print("\(somePoint) is on the x-axis")
    case (0, _):
        print("\(somePoint) is on the y-axis")
    case (-2...2, -2...2):
        print("\(somePoint) is inside the box")
    default:
        print("\(somePoint) is outside of the box")
    }
    // 输出 "(1, 1) is inside the box"
    
    • case分支允许将匹配的值声明为临时常量或变量,并且在 case 分支体内使用 —— 这种行为被称为值绑定
    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))")
    }
    // 输出 "on the x-axis with an x value of 2"
    

    请注意,这个 switch 语句不包含默认分支。这是因为最后一个 case ——case let(x, y) 声明了一个可以匹配余下所有值的元组。这使得 switch 语句已经完备了,因此不需要再书写默认分支。

    • case 分支的模式可以使用 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")
    }
    // 输出 "(1, -1) is on the line x == -y"
    
    • 当多个条件可以使用同一种方法来处理时,可以将这几种可能放在同一个 case 后面,并且用逗号隔开
    let someCharacter: Character = "e"
    switch someCharacter {
    case "a", "e", "i", "o", "u":
        print("\(someCharacter) is a vowel")
    case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
         "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
        print("\(someCharacter) is a consonant")
    default:
        print("\(someCharacter) is not a vowel or a consonant")
    }
    // 输出 "e is a vowel"
    
    • 复合匹配同样可以包含值绑定。复合匹配里所有的匹配模式,都必须包含相同的值绑定。并且每一个绑定都必须获取到相同类型的值。这保证了,无论复合匹配中的哪个模式发生了匹配,分支体内的代码,都能获取到绑定的值,并且绑定的值都有一样的类型。
    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")
    }
    // 输出 "On an axis, 9 from the origin"
    

    四、控制转移语句(Control Transfer Statements)

    • 控制转移语句改变你代码的执行顺序,通过它可以实现代码的跳转
    // Swift 有五种控制转移语句:
    continue
    break
    fallthrough
    return
    throw
    
    1、Continue
    • continue 语句告诉一个循环体立刻停止本次循环,重新开始下次循环。

    • 下面的例子把一个小写字符串中的元音字母和空格字符移除,生成了一个含义模糊的短句:

    let puzzleInput = "great minds think alike"
    var puzzleOutput = ""
    for character in puzzleInput {
        switch character {
        case "a", "e", "i", "o", "u", " ":
            continue
        default:
            puzzleOutput.append(character)
        }
    }
    print(puzzleOutput)
        // 输出 "grtmndsthnklk"
    
    2、Break
    • break语句会立刻结束整个控制流的执行。break 可以在 switch 或循环语句中使用,用来提前结束 switch 或循环语句。
    循环语句中的 break
    
    当在一个循环体中使用 break 时,会立刻中断该循环体的执行,
    然后跳转到表示循环体结束的大括号(})后的第一行代码。
    不会再有本次循环的代码被执行,也不会再有下次的循环产生。
    
    Switch 语句中的 break
    
    当在一个 switch 代码块中使用 break 时,
    会立即中断该 switch 代码块的执行,
    并且跳转到表示 switch 代码块结束的大括号(})后的第一行代码。
    
    • 下面的例子通过 switch 来判断一个 Character 值是否代表下面四种语言之一。为了简洁,多个值被包含在了同一个分支情况中。
    let numberSymbol: Character = "三"  // 简体中文里的数字 3
    var possibleIntegerValue: Int?
    switch numberSymbol {
    case "1", "١", "一", "๑":
        possibleIntegerValue = 1
    case "2", "٢", "二", "๒":
        possibleIntegerValue = 2
    case "3", "٣", "三", "๓":
        possibleIntegerValue = 3
    case "4", "٤", "四", "๔":
        possibleIntegerValue = 4
    default:
        break
    }
    if let integerValue = possibleIntegerValue {
        print("The integer value of \(numberSymbol) is \(integerValue).")
    } else {
        print("An integer value could not be found for \(numberSymbol).")
    }
    // 输出 "The integer value of 三 is 3."
    
    3、贯穿(Fallthrough)
    • fallthrough关键字可以贯穿case分支
    let integerToDescribe = 5
    var description = "The number \(integerToDescribe) is"
    switch integerToDescribe {
    case 2, 3, 5, 7, 11, 13, 17, 19:
        description += " a prime number, and also"
        fallthrough
    default:
        description += " an integer."
    }
    print(description)
    // 输出 "The number 5 is a prime number, and also an integer."
    

    注意
    fallthrough 关键字不会检查它下一个将会落入执行的 case 中的匹配条件。fallthrough 简单地使代码继续连接到下一个 case 中的代码,这和 C 语言标准中的 switch 语句特性是一样的。

    4、带标签的语句
    • 声明一个带标签的语句是通过在该语句的关键词的同一行前面放置一个标签,作为这个语句的前导关键字,并且该标签后面跟随一个冒号。

    • 下面是一个针对 while 循环体的标签语法,同样的规则适用于所有的循环体和条件语句。

    label name: while condition {
         statements
     }
    

    五、提前退出

    • if 语句一样,guard 的执行取决于一个表达式的布尔值。

    • 我们可以使用 guard 语句来要求条件必须为真时,以执行 guard 语句后的代码。

    • 不同于 if 语句,一个 guard 语句总是有一个 else 从句,如果条件不为真则执行 else 从句中的代码。

    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 is nice near you.")
            return
        }
        print("I hope the weather is nice in \(location).")
    }
    greet(["name": "John"])
    // 输出 "Hello John!"
    // 输出 "I hope the weather is nice near you."
    greet(["name": "Jane", "location": "Cupertino"])
    // 输出 "Hello Jane!"
    // 输出 "I hope the weather is nice in Cupertino."
    
    • 如果 guard 语句的条件被满足,则继续执行 guard 语句大括号后的代码。

    • 将变量或者常量的可选绑定作为 guard 语句的条件,都可以保护 guard 语句后面的代码。

    • 如果条件不被满足,在 else 分支上的代码就会被执行。这个分支必须转移控制以退出 guard 语句出现的代码段。它可以用控制转移语句如 return,break,continue 或者 throw 做这件事,或者调用一个不返回的方法或函数,例如 fatalError()

    • 相比于可以实现同样功能的 if 语句,按需使用 guard 语句会提升我们代码的可读性。它可以使你的代码连贯的被执行而不需要将它包在 else 块中,它可以使你在紧邻条件判断的地方,处理违规的情况。

    六、检测 API 可用性

    • Swift 内置支持检查 API 可用性,这可以确保我们不会在当前部署机器上,不小心地使用了不可用的 API。
    if #available(iOS 10, macOS 10.12, *) {
        // 在 iOS 使用 iOS 10 的 API, 在 macOS 使用 macOS 10.12 的 API
    } else {
        // 使用先前版本的 iOS 和 macOS 的 API
    }
    
    • 以上可用性条件指定,if 语句的代码块仅仅在 iOS 10macOS 10.12 及更高版本才运行。最后一个参数,*,是必须的,用于指定在所有其它平台中,如果版本号高于你的设备指定的最低版本,if 语句的代码块将会运行。

    • 在它一般的形式中,可用性条件使用了一个平台名字和版本的列表。平台名字可以是 iOSmacOSwatchOStvOS

    • 除了指定像 iOS 8 或 macOS 10.10 的大版本号,也可以指定像 iOS 11.2.6 以及 macOS 10.13.3 的小版本号。

    if #available(platform name version, ..., *) {
        APIs 可用,语句将执行
    } else {
        APIs 不可用,语句将不执行
    }
    

    相关文章

      网友评论

          本文标题:Swift:控制流

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