不推荐使用 Swift C 样式循环后循环中的递减索引 [英] Decrement index in a loop after Swift C-style loops deprecated

查看:37
本文介绍了不推荐使用 Swift C 样式循环后循环中的递减索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何在 Swift 3.0 中表达递减索引循环,其中以下语法不再有效?

How would you express a decrementing indexed loop in Swift 3.0, where the syntax below is not valid any more?

for var index = 10 ; index > 0; index-=1{
   print(index)
}

// 10 9 8 7 6 5 4 3 2 1

推荐答案

这里有一个更简单(也更 Swifty)的方法.

Here is an easier (and more Swifty) approach.

for i in (0 ..< 5).reversed() {
    print(i) // 4,3,2,1,0
}

let array = ["a", "b", "c", "d", "e"]
for element in array.reversed() {
    print(element) // e,d,c,b,a
}

array.reversed().forEach { print($0) } // e,d,c,b,a

print(Array(array.reversed())) // e,d,c,b,a

这篇关于不推荐使用 Swift C 样式循环后循环中的递减索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆