Swift 循环控制

2021-01-13  本文已影响0人  孤雁_南飞
  1. 使用 for-in循环来遍历序列,比如一个范围的数字,数组中的元素或者字符串中的字符
for index in 0...3 {
    print(index)
}
for char in "hello,world!" {
    print(char)
}
let names = ["张三", "李四", "王五", "赵六"]
for name in names {
    print(name)
}
  1. for-in 遍历字典:当字典遍历时,每个元素都返回(key, value)元组,你可以在 for-in循环体重使用显式命名常量来分解(key, value) 元组成员
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName) has \(legCount) legs")
}
for t in numberOfLegs {
    print("\(t.0) has \(t.1) legs")
}

3.如果你不需要序列的每一个值,你可以使用下划线来取代遍历名以忽略值

let base = 2
let power = 5
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")

4.for-in 分段区间: 使用stride(from:to:by:)函数来跳过不想要的标记(开区间)
5.闭区间也同样适用,使用stride(from:through:by:)即可

let minuteInterval = 5
for tickMark in stride(from: 0, to: 30, by: minuteInterval) {
    print(tickMark)
}
for tickMark in stride(from: 0, through: 30, by: minuteInterval) {
    print(tickMark)
}
  1. repeat-while 循环 (相当于 Objectiv-C 中的 do-while)
var count = 0
repeat {
    print(count)
    count += 1
} while  count < 5

退出多个循环

one: for i in 0...10 {
    two: for j in 0...10 {
        if j == 5 {
            break two //退出到以two 标注的循环
        }
        if i == 2 {
            break one //退出循环
        }
        print("\(i) * \(j) = \(i * j)")
    }
}

上一篇 下一篇

猜你喜欢

热点阅读