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

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

问题描述

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

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

 用于 510..509 中的索引{变量 a = 10}

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

解决方案

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

要以相反的顺序迭代范围,它们可以如下使用:

 for index in stride(from: 5, to: 1, by: -1) {打印(索引)}//打印 5, 4, 3, 2对于跨步索引(从:5,通过:1,通过:-1){打印(索引)}//打印 5, 4, 3, 2, 1

请注意,它们都不是 Range 成员函数.它们是返回 StrideToStrideThrough 结构的全局函数,它们的定义与 Range 结构不同.

此答案的先前版本使用了 Range 结构的 by() 成员函数,该成员函数已在 beta 4 中删除.如果您想了解它是如何工作的, 检查编辑历史.

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 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

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.

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.

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

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