如何在swift中以相反的顺序迭代循环? [英] How to iterate for loop in reverse order in swift?

查看:132
本文介绍了如何在swift中以相反的顺序迭代循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Playground中使用for循环时,一切正常,直到我将for循环的第一个参数更改为最高值。 (按降序迭代)

When I use the for loop in Playground, everything worked fine, until I changed the first parameter of for loop to be the highest value. (iterated in descending order)

这是一个错误吗?还有其他人有吗?

Is this a bug? Did any one else have it?

for index in 510..509
{
    var a = 10
}

显示将执行的迭代次数的计数器一直在滴答作响。 ..

The counter that displays the number of iterations that will be executions keeps ticking...

推荐答案

Xcode 6 beta 4添加了两个函数来迭代范围而不是一步:
stride(from:to:by:),用于独占范围和 stride(来自:through:by:),使用包含范围。

Xcode 6 beta 4 added two functions to iterate on ranges with a step other than one: stride(from: to: by:), which is used with exclusive ranges and stride(from: through: by:), which is used with inclusive ranges.

要按相反顺序迭代某个范围,可按以下方式使用它们:

To iterate on a range in reverse order, they can be used as below:

for index in stride(from: 5, to: 1, by: -1) {
    print(index)
}
//prints 5, 4, 3, 2

for index in stride(from: 5, through: 1, by: -1) {
    print(index)
}
//prints 5, 4, 3, 2, 1

注意这些都不是 Range 成员函数。它们是返回全局函数或者是 StrideTo StrideThrough 结构,这是从所述<$ C $不同地定义c>范围 struct。

Note that neither of those is a Range member function. They are global functions that return either a StrideTo or a StrideThrough struct, which are defined differently from the Range struct.

此答案的先前版本使用 by() 范围结构的成员函数,已在测试版4中删除。如果您想查看其工作原理,请查看编辑历史记录。

A previous version of this answer used the by() member function of the Range struct, which was removed in beta 4. If you want to see how that worked, check the edit history.

这篇关于如何在swift中以相反的顺序迭代循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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