- 使用for - in 循环遍历序列,比如一个范围的数字,数组中的元素或者字符串中的字符。
- 当字典遍历时,每一个元素都返回一个(key,value)元组,你可以在for-in循环中使用显式命名常量来分解(key,value)元组成员。
- 如果不需要序列的每一个值,你可以使用下划线来取代遍历名以忽略值。
- 使用stride(from:to:by)函数来跳过不想要的标记(开区间)。
- 闭区间也同样使用,使用stride(from:through:by)即可。
- Repeat - while 循环(Object-C do-while)。
import UIKit//1、for in 遍历区间
for index in 0...3{
print(index)//结果:0、1、2、3
}//2、for in 遍历字符
for c in "hellow" {print(c)//结果:h、e、l、l、o、w
}
//3、for in 遍历数组
let names = ["mary","jack","yoke"]
for name in names {print(name)//结果:mary、jack、yoke
}//4、for in 遍历字典let dicValue = ["city_1":"shanghai","city_2":"xian","city_3":"beijing"]for dict in dicValue {print("key is \(dict.key) value is \(dict.value)")/** 结果:key is city_2 value is xiankey is city_1 value is shanghaikey is city_3 value is beijing*/
}for (key,value) in dicValue{print("key is \(key) value is \(value)")/** 结果:key is city_2 value is xiankey is city_1 value is shanghaikey is city_3 value is beijing*/
}//5、for in 区间for i in stride(from: 0, to: 6, by: 2){
print(i)//结果 0 2 4
}for i in stride(from: 0, through: 6, by: 2){
print(i)//结果 0 2 4 6
}