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)
当我在操场上使用for循环时,一切都运行得很好,直到我将for循环的第一个参数更改为最高值。(降序)迭代
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...
显示将要执行的迭代次数的计数器一直在工作……
12 个解决方案
#1
143
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.
Xcode 6 beta 4增加了两个函数来迭代范围,步骤不是一个:stride(from: to: by:),它用于独占范围,stride(from: through: by:)用于包含范围。
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.
注意,这两个函数都不是范围成员函数。它们是返回StrideTo或StrideThrough struct的全局函数,它们与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.
这个答案的前一个版本使用了Range struct的by()成员函数,在beta 4中被删除。如果您想查看它是如何工作的,请查看编辑历史记录。
#2
183
Apply the reverse function to the range to iterate backwards:
将反向函数应用到范围内,进行反向迭代:
For Swift 1.2 and earlier:
Swift 1.2及之前版本:
// Print 10 through 1
for i in reverse(1...10) {
println(i)
}
It also works with half-open ranges:
它也适用于半开放范围:
// Print 9 through 1
for i in reverse(1..<10) {
println(i)
}
Note: reverse(1...10)
creates an array of type [Int]
, so while this might be fine for small ranges, it would be wise to use lazy
as shown below or consider the accepted stride
answer if your range is large.
注意:反向(1…10)创建一个类型数组[Int],因此,虽然这对于小范围来说可能很好,但是如果您的范围很大,那么使用lazy就很明智了。
To avoid creating a large array, use lazy
along with reverse()
. The following test runs efficiently in a Playground showing it is not creating an array with one trillion Int
s!
要避免创建大型数组,请使用lazy和reverse()。下面的测试有效地运行在一个操场上,显示它不是创建一个有一万亿字节的数组!
Test:
测试:
var count = 0
for i in lazy(1...1_000_000_000_000).reverse() {
if ++count > 5 {
break
}
println(i)
}
For Swift 2.0 in Xcode 7:
Xcode 7中的Swift 2.0:
for i in (1...10).reverse() {
print(i)
}
Note that in Swift 2.0, (1...1_000_000_000_000).reverse()
is of type ReverseRandomAccessCollection<(Range<Int>)>
, so this works fine:
注意,在Swift 2.0中,(1…1_000_000_000_000_000_000_000).reverse()类型为ReverseRandomAccessCollection<(Range
var count = 0
for i in (1...1_000_000_000_000).reverse() {
count += 1
if count > 5 {
break
}
print(i)
}
For Swift 3.0 reverse()
has been renamed to reversed()
:
Swift 3.0反向()已改名为反向():
for i in (1...10).reversed() {
print(i) // prints 10 through 1
}
#3
65
Updated for Swift 3
更新快3
The answer below is a summary of the available options. Choose the one that best fits your needs.
下面的答案是可用选项的总结。选择最适合你需要的。
reversed
: numbers in a range
Forward
向前
for index in 0..<5 {
print(index)
}
// 0
// 1
// 2
// 3
// 4
Backward
落后的
for index in (0..<5).reversed() {
print(index)
}
// 4
// 3
// 2
// 1
// 0
reversed
: elements in SequenceType
let animals = ["horse", "cow", "camel", "sheep", "goat"]
Forward
向前
for animal in animals {
print(animal)
}
// horse
// cow
// camel
// sheep
// goat
Backward
落后的
for animal in animals.reversed() {
print(animal)
}
// goat
// sheep
// camel
// cow
// horse
reversed
: elements with an index
Sometimes an index is needed when iterating through a collection. For that you can use enumerate()
, which returns a tuple. The first element of the tuple is the index and the second element is the object.
在迭代一个集合时,有时需要索引。为此,可以使用enumerate(),它返回一个元组。元组的第一个元素是索引,第二个元素是对象。
let animals = ["horse", "cow", "camel", "sheep", "goat"]
Forward
向前
for (index, animal) in animals.enumerated() {
print("\(index), \(animal)")
}
// 0, horse
// 1, cow
// 2, camel
// 3, sheep
// 4, goat
Backward
落后的
for (index, animal) in animals.enumerated().reversed() {
print("\(index), \(animal)")
}
// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse
Note that as Ben Lachman noted in his answer, you probably want to do .enumerated().reversed()
rather than .reversed().enumerated()
(which would make the index numbers increase).
请注意,正如Ben Lachman在他的答案中所指出的,您可能希望执行. enum灵().reverse(),而不是.reverse (). enum灵()(这会使索引号增加)。
stride: numbers
Stride is way to iterate without using a range. There are two forms. The comments at the end of the code show what the range version would be (assuming the increment size is 1).
Stride是不使用范围进行迭代的方法。有两种形式。代码末尾的注释显示了范围版本(假设增量大小为1)。
startIndex.stride(to: endIndex, by: incrementSize) // startIndex..<endIndex
startIndex.stride(through: endIndex, by: incrementSize) // startIndex...endIndex
Forward
向前
for index in stride(from: 0, to: 5, by: 1) {
print(index)
}
// 0
// 1
// 2
// 3
// 4
Backward
落后的
Changing the increment size to -1
allows you to go backward.
将增量大小更改为-1允许向后移动。
for index in stride(from: 4, through: 0, by: -1) {
print(index)
}
// 4
// 3
// 2
// 1
// 0
Note the to
and through
difference.
注意到和通过不同。
stride: elements of SequenceType
Forward by increments of 2
向前增加2
let animals = ["horse", "cow", "camel", "sheep", "goat"]
I'm using 2
in this example just to show another possibility.
我在这个例子中使用2只是为了展示另一种可能性。
for index in stride(from: 0, to: 5, by: 2) {
print("\(index), \(animals[index])")
}
// 0, horse
// 2, camel
// 4, goat
Backward
落后的
for index in stride(from: 4, through: 0, by: -1) {
print("\(index), \(animals[index])")
}
// 0, horse
// 1, cow
// 2, camel
// 3, sheep
// 4, goat
Notes
-
@matt has an interesting solution where he defines his own reverse operator and calls it
>>>
. It doesn't take much code to define and is used like this:@matt有一个有趣的解决方案,他定义了自己的反向运算符,并称之为>>>。它不需要很多代码来定义,它是这样使用的:
for index in 5>>>0 { print(index) } // 4 // 3 // 2 // 1 // 0
-
Check out On C-Style For Loops Removed from Swift 3
查看从Swift 3中删除的c型循环
#4
35
Swift 4 onwards
斯威夫特4起
for i in stride(from: 5, to: 0, by: -1) {
print(i)
}
//prints 5, 4, 3, 2, 1
for i in stride(from: 5, through: 0, by: -1) {
print(i)
}
//prints 5, 4, 3, 2, 1, 0
#5
23
For Swift 2.0 and above you should apply reverse on a range collection
对于Swift 2.0和以上版本,您应该对范围集合应用反向操作
for i in (0 ..< 10).reverse() {
// process
}
It has been renamed to .reversed() in Swift 3.0
它在Swift 3.0中被重命名为.reverse ()
#6
15
With Swift 3, according to your needs, you may choose one of the eight following Playground code implementations in order to solve your problem.
使用Swift 3,根据您的需要,您可以选择以下八个游乐场代码实现之一,以解决您的问题。
#1. Using CountableClosedRange
reversed()
method
CountableClosedRange
has a method called reversed()
. reversed()
method has the following declaration:
CountableClosedRange有一个名为reverse()的方法。反转()方法有以下声明:
func reversed() -> ReversedRandomAccessCollection<CountableClosedRange<Bound>>
Returns a view presenting the elements of the collection in reverse order.
返回以相反顺序显示集合元素的视图。
Usage:
用法:
let reversedRandomAccessCollection = (0 ... 5).reversed()
for index in reversedRandomAccessCollection {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#2. Using CountableRange
reversed()
method
CountableRange
has a method called reversed()
. reversed()
method has the following declaration:
CountableRange有一个名为reverse()的方法。反转()方法有以下声明:
func reversed() -> ReversedRandomAccessCollection<CountableRange<Bound>>
Returns a view presenting the elements of the collection in reverse order.
返回以相反顺序显示集合元素的视图。
Usage:
用法:
let reversedRandomAccessCollection = (0 ..< 6).reversed()
for index in reversedRandomAccessCollection {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#3. Using sequence(first:next:)
function
Swift Standard Library provides a function called sequence(first:next:)
. sequence(first:next:)
has the following declaration:
Swift标准库提供了一个名为sequence(first:next:)的函数。序列(first:next:)具有以下声明:
func sequence<T>(first: T, next: @escaping (T) -> T?) -> UnfoldSequence<T, (T?, Bool)>
Returns a sequence formed from
first
and repeated lazy applications ofnext
.返回一个由第一个和重复的惰性应用程序组成的序列。
Usage:
用法:
let unfoldSequence = sequence(first: 5, next: {
$0 > 0 ? $0 - 1 : nil
})
for index in unfoldSequence {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#4. Using stride(from:through:by:)
function
Swift Standard Library provides a function called stride(from:through:by:)
. stride(from:through:by:)
has the following declaration:
Swift标准库提供了一个名为stride(from:through:by:)的函数。大步(从:通过:by:)有以下声明:
func stride<T>(from start: T, through end: T, by stride: T.Stride) -> StrideThrough<T> where T : Strideable
Returns the sequence of values
(self, self + stride, self + 2 * stride, … last)
where last is the last value in the progression less than or equal toend
.返回值序列(self, self + stride, self + 2 * stride,……last),其中最后一个值是小于或等于end的级数中的最后一个值。
Usage:
用法:
let sequence = stride(from: 5, through: 0, by: -1)
for index in sequence {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#5. Using stride(from:to:by:)
function
Swift Standard Library provides a function called stride(from:to:by:)
. stride(from:to:by:)
has the following declaration:
Swift标准库提供了一个名为stride(from:to:by:)的函数。大步(从:到:by:)有以下声明:
func stride<T>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> where T : Strideable
Returns the sequence of values
(self, self + stride, self + 2 * stride, … last)
where last is the last value in the progression that is less thanend
.返回值序列(self, self + stride, self + 2 * stride,……last),其中last是小于end的级数中的最后一个值。
Usage:
用法:
let sequence = stride(from: 5, to: -1, by: -1)
for index in sequence {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#6. Using AnyIterator
init(_:)
initializer
AnyIterator
has an initializer called init(_:)
. init(_:)
has the following declaration:
AnyIterator有一个名为init(_:)的初始化器。init(_:)有以下声明:
init<I>(_ base: I) where I : IteratorProtocol, I.Element == Element
Creates an iterator that wraps a base iterator but whose type depends only on the base iterator’s element type.
创建一个包含基本迭代器的迭代器,但它的类型仅依赖于基本迭代器的元素类型。
Usage:
用法:
var index = 5
guard index >= 0 else { fatalError("index must be positive or equal to zero") }
let iterator = AnyIterator<Int>({
defer { index = index - 1 }
return index >= 0 ? index : nil
})
for index in iterator {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#7. Using AnyIterator
init(_:)
initializer
AnyIterator
has an initializer called init(_:)
. init(_:)
has the following declaration:
AnyIterator有一个名为init(_:)的初始化器。init(_:)有以下声明:
init(_ body: @escaping () -> AnyIterator.Element?)
Creates an iterator that wraps the given closure in its
next()
method.创建一个迭代器,在其next()方法中包装给定的闭包。
Usage:
用法:
var index = 5
guard index >= 0 else { fatalError("index must be positive or equal to zero") }
let iterator = AnyIterator({ () -> Int? in
defer { index = index - 1 }
return index >= 0 ? index : nil
})
for index in iterator {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#8. Using a custom Int
extension method
You can refactor the previous code by creating an extension method for Int
and wrapping your iterator in it:
您可以通过为Int创建一个扩展方法并将迭代器包装在其中,从而重构前面的代码:
extension Int {
func iterateDownTo(_ endIndex: Int) -> AnyIterator<Int> {
var index = self
guard index >= endIndex else { fatalError("self must be greater than or equal to endIndex") }
let iterator = AnyIterator { () -> Int? in
defer { index = index - 1 }
return index >= endIndex ? index : nil
}
return iterator
}
}
let iterator = 5.iterateDownTo(0)
for index in iterator {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#7
6
In Swift 4 and latter
在斯威夫特4和后者
let count = 50//For example
for i in (1...count).reversed() {
print(i)
}
#8
5
Swift 4.0
斯威夫特4.0
for i in stride(from: 5, to: 0, by: -1) {
print(i) // 5,4,3,2,1
}
If you want to include the to
value:
如果你想要包含价值:
for i in stride(from: 5, through: 0, by: -1) {
print(i) // 5,4,3,2,1,0
}
#9
3
If one is wanting to iterate through an array (Array
or more generally any SequenceType
) in reverse. You have a few additional options.
如果想要反向遍历数组(数组或更一般的任何顺序类型)。你有一些额外的选择。
First you can reverse()
the array and loop through it as normal. However I prefer to use enumerate()
much of the time since it outputs a tuple containing the object and it's index.
首先,可以反向()数组并按常规循环。但是,我更喜欢使用enumerate(),因为它输出一个包含对象及其索引的元组。
The one thing to note here is that it is important to call these in the right order:
这里需要注意的一点是,以正确的顺序调用它们是很重要的:
for (index, element) in array.enumerate().reverse()
for (index, element) in array.enumerate().reverse()
yields indexes in descending order (which is what I generally expect). whereas:
按降序生成索引(这是我通常期望的)。而:
for (index, element) in array.reverse().enumerate()
(which is a closer match to NSArray's reverseEnumerator
)
for (index, element) in array.reverse().enumerate()(与NSArray的reverseEnumerator更接近)
walks the array backward but outputs ascending indexes.
向后遍历数组,但输出升序索引。
#10
2
as for Swift 2.2 , Xcode 7.3 (10,June,2016) :
Swift 2.2、Xcode 7.3(2016年6月10日):
for (index,number) in (0...10).enumerate() {
print("index \(index) , number \(number)")
}
for (index,number) in (0...10).reverse().enumerate() {
print("index \(index) , number \(number)")
}
Output :
输出:
index 0 , number 0
index 1 , number 1
index 2 , number 2
index 3 , number 3
index 4 , number 4
index 5 , number 5
index 6 , number 6
index 7 , number 7
index 8 , number 8
index 9 , number 9
index 10 , number 10
index 0 , number 10
index 1 , number 9
index 2 , number 8
index 3 , number 7
index 4 , number 6
index 5 , number 5
index 6 , number 4
index 7 , number 3
index 8 , number 2
index 9 , number 1
index 10 , number 0
#11
1
var sum1 = 0
for i in 0...100{
sum1 += i
}
print (sum1)
for i in (10...100).reverse(){
sum1 /= i
}
print(sum1)
#12
1
You can consider using the C-Style while
loop instead. This works just fine in Swift 3:
您可以考虑使用C-Style while循环。这在Swift 3中很有效:
var i = 5
while i > 0 {
print(i)
i -= 1
}
#1
143
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.
Xcode 6 beta 4增加了两个函数来迭代范围,步骤不是一个:stride(from: to: by:),它用于独占范围,stride(from: through: by:)用于包含范围。
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.
注意,这两个函数都不是范围成员函数。它们是返回StrideTo或StrideThrough struct的全局函数,它们与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.
这个答案的前一个版本使用了Range struct的by()成员函数,在beta 4中被删除。如果您想查看它是如何工作的,请查看编辑历史记录。
#2
183
Apply the reverse function to the range to iterate backwards:
将反向函数应用到范围内,进行反向迭代:
For Swift 1.2 and earlier:
Swift 1.2及之前版本:
// Print 10 through 1
for i in reverse(1...10) {
println(i)
}
It also works with half-open ranges:
它也适用于半开放范围:
// Print 9 through 1
for i in reverse(1..<10) {
println(i)
}
Note: reverse(1...10)
creates an array of type [Int]
, so while this might be fine for small ranges, it would be wise to use lazy
as shown below or consider the accepted stride
answer if your range is large.
注意:反向(1…10)创建一个类型数组[Int],因此,虽然这对于小范围来说可能很好,但是如果您的范围很大,那么使用lazy就很明智了。
To avoid creating a large array, use lazy
along with reverse()
. The following test runs efficiently in a Playground showing it is not creating an array with one trillion Int
s!
要避免创建大型数组,请使用lazy和reverse()。下面的测试有效地运行在一个操场上,显示它不是创建一个有一万亿字节的数组!
Test:
测试:
var count = 0
for i in lazy(1...1_000_000_000_000).reverse() {
if ++count > 5 {
break
}
println(i)
}
For Swift 2.0 in Xcode 7:
Xcode 7中的Swift 2.0:
for i in (1...10).reverse() {
print(i)
}
Note that in Swift 2.0, (1...1_000_000_000_000).reverse()
is of type ReverseRandomAccessCollection<(Range<Int>)>
, so this works fine:
注意,在Swift 2.0中,(1…1_000_000_000_000_000_000_000).reverse()类型为ReverseRandomAccessCollection<(Range
var count = 0
for i in (1...1_000_000_000_000).reverse() {
count += 1
if count > 5 {
break
}
print(i)
}
For Swift 3.0 reverse()
has been renamed to reversed()
:
Swift 3.0反向()已改名为反向():
for i in (1...10).reversed() {
print(i) // prints 10 through 1
}
#3
65
Updated for Swift 3
更新快3
The answer below is a summary of the available options. Choose the one that best fits your needs.
下面的答案是可用选项的总结。选择最适合你需要的。
reversed
: numbers in a range
Forward
向前
for index in 0..<5 {
print(index)
}
// 0
// 1
// 2
// 3
// 4
Backward
落后的
for index in (0..<5).reversed() {
print(index)
}
// 4
// 3
// 2
// 1
// 0
reversed
: elements in SequenceType
let animals = ["horse", "cow", "camel", "sheep", "goat"]
Forward
向前
for animal in animals {
print(animal)
}
// horse
// cow
// camel
// sheep
// goat
Backward
落后的
for animal in animals.reversed() {
print(animal)
}
// goat
// sheep
// camel
// cow
// horse
reversed
: elements with an index
Sometimes an index is needed when iterating through a collection. For that you can use enumerate()
, which returns a tuple. The first element of the tuple is the index and the second element is the object.
在迭代一个集合时,有时需要索引。为此,可以使用enumerate(),它返回一个元组。元组的第一个元素是索引,第二个元素是对象。
let animals = ["horse", "cow", "camel", "sheep", "goat"]
Forward
向前
for (index, animal) in animals.enumerated() {
print("\(index), \(animal)")
}
// 0, horse
// 1, cow
// 2, camel
// 3, sheep
// 4, goat
Backward
落后的
for (index, animal) in animals.enumerated().reversed() {
print("\(index), \(animal)")
}
// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse
Note that as Ben Lachman noted in his answer, you probably want to do .enumerated().reversed()
rather than .reversed().enumerated()
(which would make the index numbers increase).
请注意,正如Ben Lachman在他的答案中所指出的,您可能希望执行. enum灵().reverse(),而不是.reverse (). enum灵()(这会使索引号增加)。
stride: numbers
Stride is way to iterate without using a range. There are two forms. The comments at the end of the code show what the range version would be (assuming the increment size is 1).
Stride是不使用范围进行迭代的方法。有两种形式。代码末尾的注释显示了范围版本(假设增量大小为1)。
startIndex.stride(to: endIndex, by: incrementSize) // startIndex..<endIndex
startIndex.stride(through: endIndex, by: incrementSize) // startIndex...endIndex
Forward
向前
for index in stride(from: 0, to: 5, by: 1) {
print(index)
}
// 0
// 1
// 2
// 3
// 4
Backward
落后的
Changing the increment size to -1
allows you to go backward.
将增量大小更改为-1允许向后移动。
for index in stride(from: 4, through: 0, by: -1) {
print(index)
}
// 4
// 3
// 2
// 1
// 0
Note the to
and through
difference.
注意到和通过不同。
stride: elements of SequenceType
Forward by increments of 2
向前增加2
let animals = ["horse", "cow", "camel", "sheep", "goat"]
I'm using 2
in this example just to show another possibility.
我在这个例子中使用2只是为了展示另一种可能性。
for index in stride(from: 0, to: 5, by: 2) {
print("\(index), \(animals[index])")
}
// 0, horse
// 2, camel
// 4, goat
Backward
落后的
for index in stride(from: 4, through: 0, by: -1) {
print("\(index), \(animals[index])")
}
// 0, horse
// 1, cow
// 2, camel
// 3, sheep
// 4, goat
Notes
-
@matt has an interesting solution where he defines his own reverse operator and calls it
>>>
. It doesn't take much code to define and is used like this:@matt有一个有趣的解决方案,他定义了自己的反向运算符,并称之为>>>。它不需要很多代码来定义,它是这样使用的:
for index in 5>>>0 { print(index) } // 4 // 3 // 2 // 1 // 0
-
Check out On C-Style For Loops Removed from Swift 3
查看从Swift 3中删除的c型循环
#4
35
Swift 4 onwards
斯威夫特4起
for i in stride(from: 5, to: 0, by: -1) {
print(i)
}
//prints 5, 4, 3, 2, 1
for i in stride(from: 5, through: 0, by: -1) {
print(i)
}
//prints 5, 4, 3, 2, 1, 0
#5
23
For Swift 2.0 and above you should apply reverse on a range collection
对于Swift 2.0和以上版本,您应该对范围集合应用反向操作
for i in (0 ..< 10).reverse() {
// process
}
It has been renamed to .reversed() in Swift 3.0
它在Swift 3.0中被重命名为.reverse ()
#6
15
With Swift 3, according to your needs, you may choose one of the eight following Playground code implementations in order to solve your problem.
使用Swift 3,根据您的需要,您可以选择以下八个游乐场代码实现之一,以解决您的问题。
#1. Using CountableClosedRange
reversed()
method
CountableClosedRange
has a method called reversed()
. reversed()
method has the following declaration:
CountableClosedRange有一个名为reverse()的方法。反转()方法有以下声明:
func reversed() -> ReversedRandomAccessCollection<CountableClosedRange<Bound>>
Returns a view presenting the elements of the collection in reverse order.
返回以相反顺序显示集合元素的视图。
Usage:
用法:
let reversedRandomAccessCollection = (0 ... 5).reversed()
for index in reversedRandomAccessCollection {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#2. Using CountableRange
reversed()
method
CountableRange
has a method called reversed()
. reversed()
method has the following declaration:
CountableRange有一个名为reverse()的方法。反转()方法有以下声明:
func reversed() -> ReversedRandomAccessCollection<CountableRange<Bound>>
Returns a view presenting the elements of the collection in reverse order.
返回以相反顺序显示集合元素的视图。
Usage:
用法:
let reversedRandomAccessCollection = (0 ..< 6).reversed()
for index in reversedRandomAccessCollection {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#3. Using sequence(first:next:)
function
Swift Standard Library provides a function called sequence(first:next:)
. sequence(first:next:)
has the following declaration:
Swift标准库提供了一个名为sequence(first:next:)的函数。序列(first:next:)具有以下声明:
func sequence<T>(first: T, next: @escaping (T) -> T?) -> UnfoldSequence<T, (T?, Bool)>
Returns a sequence formed from
first
and repeated lazy applications ofnext
.返回一个由第一个和重复的惰性应用程序组成的序列。
Usage:
用法:
let unfoldSequence = sequence(first: 5, next: {
$0 > 0 ? $0 - 1 : nil
})
for index in unfoldSequence {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#4. Using stride(from:through:by:)
function
Swift Standard Library provides a function called stride(from:through:by:)
. stride(from:through:by:)
has the following declaration:
Swift标准库提供了一个名为stride(from:through:by:)的函数。大步(从:通过:by:)有以下声明:
func stride<T>(from start: T, through end: T, by stride: T.Stride) -> StrideThrough<T> where T : Strideable
Returns the sequence of values
(self, self + stride, self + 2 * stride, … last)
where last is the last value in the progression less than or equal toend
.返回值序列(self, self + stride, self + 2 * stride,……last),其中最后一个值是小于或等于end的级数中的最后一个值。
Usage:
用法:
let sequence = stride(from: 5, through: 0, by: -1)
for index in sequence {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#5. Using stride(from:to:by:)
function
Swift Standard Library provides a function called stride(from:to:by:)
. stride(from:to:by:)
has the following declaration:
Swift标准库提供了一个名为stride(from:to:by:)的函数。大步(从:到:by:)有以下声明:
func stride<T>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> where T : Strideable
Returns the sequence of values
(self, self + stride, self + 2 * stride, … last)
where last is the last value in the progression that is less thanend
.返回值序列(self, self + stride, self + 2 * stride,……last),其中last是小于end的级数中的最后一个值。
Usage:
用法:
let sequence = stride(from: 5, to: -1, by: -1)
for index in sequence {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#6. Using AnyIterator
init(_:)
initializer
AnyIterator
has an initializer called init(_:)
. init(_:)
has the following declaration:
AnyIterator有一个名为init(_:)的初始化器。init(_:)有以下声明:
init<I>(_ base: I) where I : IteratorProtocol, I.Element == Element
Creates an iterator that wraps a base iterator but whose type depends only on the base iterator’s element type.
创建一个包含基本迭代器的迭代器,但它的类型仅依赖于基本迭代器的元素类型。
Usage:
用法:
var index = 5
guard index >= 0 else { fatalError("index must be positive or equal to zero") }
let iterator = AnyIterator<Int>({
defer { index = index - 1 }
return index >= 0 ? index : nil
})
for index in iterator {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#7. Using AnyIterator
init(_:)
initializer
AnyIterator
has an initializer called init(_:)
. init(_:)
has the following declaration:
AnyIterator有一个名为init(_:)的初始化器。init(_:)有以下声明:
init(_ body: @escaping () -> AnyIterator.Element?)
Creates an iterator that wraps the given closure in its
next()
method.创建一个迭代器,在其next()方法中包装给定的闭包。
Usage:
用法:
var index = 5
guard index >= 0 else { fatalError("index must be positive or equal to zero") }
let iterator = AnyIterator({ () -> Int? in
defer { index = index - 1 }
return index >= 0 ? index : nil
})
for index in iterator {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#8. Using a custom Int
extension method
You can refactor the previous code by creating an extension method for Int
and wrapping your iterator in it:
您可以通过为Int创建一个扩展方法并将迭代器包装在其中,从而重构前面的代码:
extension Int {
func iterateDownTo(_ endIndex: Int) -> AnyIterator<Int> {
var index = self
guard index >= endIndex else { fatalError("self must be greater than or equal to endIndex") }
let iterator = AnyIterator { () -> Int? in
defer { index = index - 1 }
return index >= endIndex ? index : nil
}
return iterator
}
}
let iterator = 5.iterateDownTo(0)
for index in iterator {
print(index)
}
/*
Prints:
5
4
3
2
1
0
*/
#7
6
In Swift 4 and latter
在斯威夫特4和后者
let count = 50//For example
for i in (1...count).reversed() {
print(i)
}
#8
5
Swift 4.0
斯威夫特4.0
for i in stride(from: 5, to: 0, by: -1) {
print(i) // 5,4,3,2,1
}
If you want to include the to
value:
如果你想要包含价值:
for i in stride(from: 5, through: 0, by: -1) {
print(i) // 5,4,3,2,1,0
}
#9
3
If one is wanting to iterate through an array (Array
or more generally any SequenceType
) in reverse. You have a few additional options.
如果想要反向遍历数组(数组或更一般的任何顺序类型)。你有一些额外的选择。
First you can reverse()
the array and loop through it as normal. However I prefer to use enumerate()
much of the time since it outputs a tuple containing the object and it's index.
首先,可以反向()数组并按常规循环。但是,我更喜欢使用enumerate(),因为它输出一个包含对象及其索引的元组。
The one thing to note here is that it is important to call these in the right order:
这里需要注意的一点是,以正确的顺序调用它们是很重要的:
for (index, element) in array.enumerate().reverse()
for (index, element) in array.enumerate().reverse()
yields indexes in descending order (which is what I generally expect). whereas:
按降序生成索引(这是我通常期望的)。而:
for (index, element) in array.reverse().enumerate()
(which is a closer match to NSArray's reverseEnumerator
)
for (index, element) in array.reverse().enumerate()(与NSArray的reverseEnumerator更接近)
walks the array backward but outputs ascending indexes.
向后遍历数组,但输出升序索引。
#10
2
as for Swift 2.2 , Xcode 7.3 (10,June,2016) :
Swift 2.2、Xcode 7.3(2016年6月10日):
for (index,number) in (0...10).enumerate() {
print("index \(index) , number \(number)")
}
for (index,number) in (0...10).reverse().enumerate() {
print("index \(index) , number \(number)")
}
Output :
输出:
index 0 , number 0
index 1 , number 1
index 2 , number 2
index 3 , number 3
index 4 , number 4
index 5 , number 5
index 6 , number 6
index 7 , number 7
index 8 , number 8
index 9 , number 9
index 10 , number 10
index 0 , number 10
index 1 , number 9
index 2 , number 8
index 3 , number 7
index 4 , number 6
index 5 , number 5
index 6 , number 4
index 7 , number 3
index 8 , number 2
index 9 , number 1
index 10 , number 0
#11
1
var sum1 = 0
for i in 0...100{
sum1 += i
}
print (sum1)
for i in (10...100).reverse(){
sum1 /= i
}
print(sum1)
#12
1
You can consider using the C-Style while
loop instead. This works just fine in Swift 3:
您可以考虑使用C-Style while循环。这在Swift 3中很有效:
var i = 5
while i > 0 {
print(i)
i -= 1
}