從swift3開始柑潦,swift放棄了c風(fēng)格的for循環(huán),而建議我們用區(qū)間運(yùn)算符的方式寫循環(huán)
c風(fēng)格
for var i = 1; i < 10 ; i += 1 {
print(i)
}
區(qū)間運(yùn)算符方式
for i in 1 ..< 10{
print(i)
}
如果想倒序循環(huán)勋乾,請使用 reversed函數(shù)
for i in (1 ..< 10).reversed(){
print(i)
}
stride函數(shù)
for i in stride( from : 0 , through : 10 , by : 2){
print(i)
//打印結(jié)果為:
//0
//2
//4
//6
//8
//10
//如果想不包含10的話,將through改成to即可 for i in stride( from : 0 , to : 10 , by : 2)
}
重要的是stride函數(shù)是支持小數(shù)的
for i in stride( from : 0 , through : 10 , by : 0.1){
print(i)
//打印結(jié)果為:
//0.0
//0.1
//0.2
//0.3
//...
//10.0
}