Swift 5 流程控制 if-else、for、switch、where、区间

if-else while repeat—while

判断的条件只能是Bool类型不能是其他类型
if 后的小括号可省略
不能用 ++ 和 -- swift3开始移除了


for

区间运算符

let range1: ClosedRange = 1..3
let range2: Range = 1..<3
let range3: PartialRangeThrough = ...3

range.contains(7) // false

区间也可以使用字符和字符串,但默认不能用在for-in中

间隔区间值


let hours = 24

let hourInterval = 2

for tickMark in stride(from: 4, through: hours, by: hourInterval) {
    print(tickMark)
}// 4 6 8 1012 14 16 18 20 22 24

for tickMark in stride(from: 1, to: 10, by: 2) {
    print(tickMark)
}//1 3 5 7 9


switch

必须保证处理所有情况,能保证处理所有情况的时候可以不使用default

支持Character、String、区间、元组

  • 基本条件和复合条件
var number = 1
switch number {
case 1, 3: // 复合条件 符合1和3的情况
    print(1)
    fallthrough // 贯穿 可以没有break case default中必须由语句
case 2:
    print(2)
default:
    print("other")
}
  • 区间匹配
let count = 5

switch count {
case 0:
    print(0)
case 1..<5 :
    print("a few")
case 5 :
    print("true")
case 6...10 :
    print("hundreds of")
default:
    print("many")
}
  • 元组匹配和值绑定
let point = (1, 1)

switch point {
case (0, 0):
    print("the origin")
case (_, 0):
    print("on the x_axis")
case (0, _):
    print("on the y_axis")
case (-2...2, -2...2):
    print("in the box")
default:
    print("other")
}

switch point {
case (var x, 1):
    print("x = \(x)")
case (1, let y):
    print("y = \(y)")
default:
    print("other")
}

  • 标签语句
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)")
    }
}


where

let point1 = (1, -1)

switch point1 {
case let (x, y) where x == y:
    print("x==y \(x)")
case let (x, y) where x == -y:
    print("x==-y")
default:
    print("other")
}


var nums = [10, 20, 30, -20, -10 , -30]
var sum = 0
for num in nums where num > 0 {
    sum += num
}
print(sum)

你可能感兴趣的:(Swift 5 流程控制 if-else、for、switch、where、区间)