Image Description

条件语句用来控制代码的执行路径,常见的 if ... else 就是条件判断语句。

条件分支判断

用 if ... else if ... else

var date = "sunday"

var action = ""

if date == "sunday" {
  action = "go to park"
} else if date == "saturday" {
  action = "go to restaurant"
} else {
  action = "go to company"
}

switch .. case 条件判断

switch date {
  case "sunday":
    action = "go to park"
  case "saturday":
    action = "go to restaurant"
  default:
    action = "go to company"
}

循环控制语句

for ... in 循环控制

let name = ["码", "客", "南", "君"]

for char in name {
  print(char)
}
// 码客南君

for number in 5...10 {
  print(number)
}
// 5 6 7 8 9 10

while 循环控制

var i  = 0

while i < 10 {
  print(i)
  i += 1
}

当 i 小于 10的时候,输出 i并将 i加1