for-in循环
- 使用 for-in 循环来遍历序列,比如一个范围的数字,数组中的元素或者字符串中的字符。
- 当字典遍历时,每一个元素都返回一个(key,value)元组,你可以在 for-in 循环体中使用显示命名常量来分解(key,value)元组成员。
- 如果你不需要序列的每一个值,你可以使用下划线来取代遍历名以忽略值。
let dict = ["spider": 8, "ant": 6, "cat": 4]
for item in dict {
print("\(item.0) has \(item.1) legs")
}
for (animalName, legCount) in dict {
print("\(animalName) has \(legCount) legs")
}
for-in分段区间
- 使用 stride(from:to:by:) 函数来跳过不想要的标记(开区间)
- 闭区间也同样适用,使用 stride(from:through:by:) 即可
for i in stride(from: 0, to: 50, by: 5) {
print(i)
}
for i in stride(from: 0, through: 50, by: 5) {
print(i)
}
while循环
- repeat-while 循环 (Objective-C do-while)
var count = 0
repeat {
print(count)
count += 1
} while count < 5
网友评论