守着星空守着你
删除for init; comparison; increment {}并删除++和--轻松。并使用Swift的漂亮for-in循环 // WARNING: C-style for statement is deprecated and will be removed in a future version of Swift
for var i = 1; i <= 10; i += 1 {
print("I'm number \(i)")
}Swift 2.2: // new swift style works well
for i in 1...10 {
print("I'm number \(i)")
}递减指数 for index in 10.stride(to: 0, by: -1) {
print(index)
}或者你可以使用reverse()像 for index in (0 ..< 10).reverse() { ... }浮球型 (there is no need to define any types to index) for index in 0.stride(to: 0.6, by: 0.1) {
print(index) //0.0 ,0.1, 0.2,0.3,0.4,0.5
}Swift 3.0:从开始Swift3.0,stride(to:by:)Strideable上的方法已替换为自由函数,stride(from:to:by:)for i in stride(from: 0, to: 10, by: 1){
print(i)}对于中的递减索引Swift 3.0,您可以使用reversed()for i in (0 ..< 5).reversed() {
print(i) // 4,3,2,1,0}其他则for each和stride(),则可以使用While Loopsvar i = 0while i < 10 {
i += 1
print(i)}Repeat-While Loop:var a = 0repeat {
a += 1
print(a)} while a < 10在《 Swift编程语言指南》中查看控制流