流程控制

if-else

  let age = 4
  if age >= 22 {
      print("Get married")
  } else if age >= 18 {
      print("Being a adult")
  } else if age >= 7 {
      print("Go to school")
  } else {
      print("Just a child")
  }


while

var num = 5
while num > 0 {
    print("num is \(num)")
    num -= 1
}//打印了5次

var num = -1
repeat {
    print("num is \(num)")
} while num > 0 //打印了1次


for


for - 区间运算符用在数组上

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names[0...3] {
    print(name)
} // Anna Alex Brian Jack

区间类型


带区间的间隔符

let hours = 11
let hourInterval = 2
//tickMark的取值:从4开始,累加2,不超过11

for tickMark in stride(from: 4, through: hours, by: hourInterval) {
    print(tickMark)
} // 4 6 8 10

switch


fallthrough


switch注意点

  var number = 1
  switch number {
  case 1:
      print("number is 1")
  case 2:
      print("number is 2")
  default:
      break
  }

复合条件


区间匹配、元组匹配


值绑定


where

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

//将所有正数加起来
var numbers = [10, 20, -10, -20, 30, 30]
var sum = 0
for num in numbers where num > 0 { // 使用where来过滤num
    sum += num
}
print(sum) // 60

标签语句

outer: for i in 1...4 {
    for k in 1...4 {
        if k == 3 {
            continue outer
        }
        if i == 3 {
            break outer
        }
        print("i == \(i), k == \(k)")
    }
}