swift2 控制流

前端之家收集整理的这篇文章主要介绍了swift2 控制流前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

For循环


for循环有两种形式,一种是for in 可以方便的变量数组等集合类型,另一张是与c语言类型的基本for循环。

for in


  1. let numberOfLegs = ["spider": 8,"ant": 6,"cat": 4]
  2. for (animalName,legCount) in numberOfLegs {
  3. print("\(animalName)s have \(legCount) legs")
  4. }
  5. // spiders have 8 legs
  6. // ants have 6 legs
  7. // cats have 4 legs


条件递增


  1. for var index = 0; index < 3; ++index {
  2. print("index is \(index)")
  3. }
  4. // index is 0
  5. // index is 1
  6. // index is 2

在初始化表达式中声明的常量和变量(比如var index = 0)只在for循环的生命周期里有效。
如果想在循环结束后访问index的值,你必须要在循环生命周期开始前声明index。


while循环


while也包括两种,while循环和repeat while循环(repeat while 就是其他语言的 do while)

while


  1. var square = 0
  2. var diceRoll = 0
  3. while square < finalSquare {
  4. // 掷骰子
  5. if ++diceRoll == 7 { diceRoll = 1 }
  6. // 根据点数移动
  7. square += diceRoll
  8. if square < board.count {
  9. // 如果玩家还在棋盘上,顺着梯子爬上去或者顺着蛇滑下去
  10. square += board[square]
  11. }
  12. }
  13. print("Game over!")


repeat while


  1. repeat {
  2. // 顺着梯子爬上去或者顺着蛇滑下去
  3. square += board[square]
  4. // 掷骰子
  5. if ++diceRoll == 7 { diceRoll = 1 }
  6. // 根据点数移动
  7. square += diceRoll
  8. } while square < finalSquare
  9. print("Game over!")

代码摘自 the swift programing language 2



if语句


  1. let temperatureInFahrenheit = 90
  2. if temperatureInFahrenheit <= 32 {
  3. print("It's very cold. Consider wearing a scarf.")
  4. } else if temperatureInFahrenheit >= 86 {
  5. print("It's really warm. Don't forget to wear sunscreen.")
  6. } else {
  7. print("It's not that cold. Wear a t-shirt.")
  8. }
  9. // 输出 "It's really warm. Don't forget to wear sunscreen."



switch语句


  1. let someCharacter: Character = "e"
  2. switch someCharacter {
  3. case "a","e","i","o","u":
  4. print("\(someCharacter) is a vowel")
  5. case "b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z":
  6. print("\(someCharacter) is a consonant")
  7. default:
  8. print("\(someCharacter) is not a vowel or a consonant")
  9. }
  10. // 输出 "e is a vowel"


与 C 语言和 Objective-C 中的switch语句不同,在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个 case 分支。
这也就是说,不需要在 case 分支中显式地使用break语句。这使得switch语句更安全、更易用,也避免了因忘记写break语句而产生的错误


区间匹配


  1. let count = 3_000_000_000_000
  2. let countedThings = "stars in the Milky Way"
  3. var naturalCount: String
  4. switch count {
  5. case 0:
  6. naturalCount = "no"
  7. case 1...3:
  8. naturalCount = "a few"
  9. case 4...9:
  10. naturalCount = "several"
  11. case 10...99:
  12. naturalCount = "tens of"
  13. case 100...999:
  14. naturalCount = "hundreds of"
  15. case 1000...999_999:
  16. naturalCount = "thousands of"
  17. default:
  18. naturalCount = "millions and millions of"
  19. }
  20. print("There are \(naturalCount) \(countedThings).")
  21. // 输出 "There are millions and millions of stars in the Milky Way."


元组匹配


你可以使用元组在同一个switch语句中测试多个值。
元组中的元素可以是值,也可以是区间。另外,使用下划线(_)来匹配所有可能的值。

  1. let somePoint = (1,1)
  2. switch somePoint {
  3. case (0,0):
  4. print("(0,0) is at the origin")
  5. case (_,0):
  6. print("(\(somePoint.0),0) is on the x-axis")
  7. case (0,_):
  8. print("(0,\(somePoint.1)) is on the y-axis")
  9. case (-2...2,-2...2):
  10. print("(\(somePoint.0),\(somePoint.1)) is inside the Box")
  11. default:
  12. print("(\(somePoint.0),\(somePoint.1)) is outside of the Box")
  13. }
  14. // 输出 "(1,1) is inside the Box"


值绑定

case 分支的模式允许将匹配的值绑定到一个临时的常量或变量.
这些常量或变量在该 case 分支里就可以被引用了——这种行为被称为值绑定(value binding)。

  1. let anotherPoint = (2,0)
  2. switch anotherPoint {
  3. case (let x,0):
  4. print("on the x-axis with an x value of \(x)")
  5. case (0,let y):
  6. print("on the y-axis with a y value of \(y)")
  7. case let (x,y):
  8. print("somewhere else at (\(x),\(y))")
  9. }
  10. // 输出 "on the x-axis with an x value of 2"


where语句

  1. let yetAnotherPoint = (1,-1)
  2. switch yetAnotherPoint {
  3. case let (x,y) where x == y:
  4. print("(\(x),\(y)) is on the line x == y")
  5. case let (x,y) where x == -y:
  6. print("(\(x),\(y)) is on the line x == -y")
  7. case let (x,y):
  8. print("\(x),\(y)) is just some arbitrary point")
  9. }
  10. // 输出 "(1,-1) is on the line x == -y"



转移控制语句


fallthrough


如果你确实需要 C 风格的贯穿(fallthrough)的特性,你可以在每个需要该特性的 case 分支中使用fallthrough关键字。
下面的例子使用fallthrough来创建一个数字的描述语句。

  1. let integerToDescribe = 5
  2. var description = "The number \(integerToDescribe) is"
  3. switch integerToDescribe {
  4. case 2,3,5,7,11,13,17,19:
  5. description += " a prime number,and also"
  6. fallthrough
  7. default:
  8. description += " an integer."
  9. }
  10. print(description)
  11. // 输出 "The number 5 is a prime number,and also an integer."


标签的语句


跟c语言的goto很像

  1. gameLoop: while square != finalSquare {
  2. if ++diceRoll == 7 { diceRoll = 1 }
  3. switch square + diceRoll {
  4. case finalSquare:
  5. // 到达最后一个方块,游戏结束
  6. break gameLoop
  7. case let newSquare where newSquare > finalSquare:
  8. // 超出最后一个方块,再掷一次骰子
  9. continue gameLoop
  10. default:
  11. // 本次移动有效
  12. square += diceRoll
  13. square += board[square]
  14. }
  15. }
  16. print("Game over!")

如果上述的break语句没有使用gameLoop标签,那么它将会中断switch代码块而不是while循环体。
使用gameLoop标签清晰的表明了break想要中断的是哪个代码块。

同时请注意,当调用continue gameLoop去跳转到下一次循环迭代时,这里使用gameLoop标签并不是严格必须的。
因为在这个游戏中,只有一个循环体,所以continue语句会影响到哪个循环体是没有歧义的。

然而,continue语句使用gameLoop标签也是没有危害的。
这样做符合标签的使用规则,同时参照旁边的break gameLoop,能够使游戏的逻辑更加清晰和易于理解。


最后还有 guard语句,看起来很像断言。

猜你在找的Swift相关文章