Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 358 Vote(s) - 3.71 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to iterate for loop in reverse order in swift?

#1
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...

![enter image description here][1]


[1]:
Reply

#2

This will works decrement by one in reverse order.

let num1 = [1,2,3,4,5]
for item in nums1.enumerated().reversed() {

print(item.offset) // Print the index number: 4,3,2,1,0
print(item.element) // Print the value :5,4,3,2,1

}

Or you can use this index, value property

let num1 = [1,2,3,4,5]
for (index,item) in nums1.enumerated().reversed() {

print(index) // Print the index number: 4,3,2,1,0
print(item) // Print the value :5,4,3,2,1

}

Reply

#3
Reversing an array can be done with just single step **.reverse()**

var arrOfnum = [1,2,3,4,5,6]
arrOfnum.reverse()
Reply

#4
> For me, this is the best way.


var arrayOfNums = [1,4,5,68,9,10]

for i in 0..<arrayOfNums.count {
print(arrayOfNums[arrayOfNums.count - i - 1])
}


Reply

#5
With Swift 5, according to your needs, you may choose one of the **four following Playground code examples** in order to solve your problem.

---

# #1. Using `ClosedRange` `reversed()` method

`ClosedRange` has a method called [`reversed()`][1]. `reversed()` method has the following declaration:

func reversed() -> ReversedCollection<ClosedRange<Bound>>

> Returns a view presenting the elements of the collection in reverse order.

*Usage:*

let reversedCollection = (0 ... 5).reversed()

for index in reversedCollection {
print(index)
}

/*
Prints:
5
4
3
2
1
0
*/


As an alternative, you can use `Range` [`reversed()`][2] method:

let reversedCollection = (0 ..< 6).reversed()

for index in reversedCollection {
print(index)
}

/*
Prints:
5
4
3
2
1
0
*/

---

# #2. Using `sequence(first:next:)` function

Swift Standard Library provides a function called [`sequence(first:next:)`][3]. `sequence(first:next:)` has the following declaration:

func sequence<T>(first: T, next: @escaping (T) -> T?) -> UnfoldFirstSequence<T>

> Returns a sequence formed from `first` and repeated lazy applications of `next`.

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

---

# #3. Using `stride(from:through:by:)` function

Swift Standard Library provides a function called [`stride(from:through:by:)`][4]. `stride(from:through:by:)` has the following declaration:

func stride<T>(from start: T, through end: T, by stride: T.Stride) -> StrideThrough<T> where T : Strideable

> Returns a sequence from a starting value toward, and possibly including, an end value, stepping by the specified amount.

*Usage:*

let sequence = stride(from: 5, through: 0, by: -1)

for index in sequence {
print(index)
}

/*
Prints:
5
4
3
2
1
0
*/

As an alternative, you can use [`stride(from:to:by:)`][5]:

let sequence = stride(from: 5, to: -1, by: -1)

for index in sequence {
print(index)
}

/*
Prints:
5
4
3
2
1
0
*/

---

# #4. Using `AnyIterator` `init(_:)` initializer

`AnyIterator` has an initializer called [`init(_:)`][6]. `init(_:)` has the following declaration:

init(_ body: @escaping () -> AnyIterator<Element>.Element?)

> Creates an iterator that wraps the given closure in its `next()` method.

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

If needed, you can refactor the previous code by creating an extension method for `Int` and wrapping your iterator in it:

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


[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

[4]:

[To see links please register here]

[5]:

[To see links please register here]

[6]:

[To see links please register here]

Reply

#6
*Updated for Swift 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.

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][2], you probably want to do `.enumerated().reversed()` rather than `.reversed().enumerated()` (which would make the index numbers increase).

#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).

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.

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

let animals = ["horse", "cow", "camel", "sheep", "goat"]

I'm using `2` in this example just to show another possibility.

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])")
}

// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse

#Notes

- @matt has [an interesting solution][3] where he defines his own reverse operator and calls it `>>>`. It doesn't take much code to define and is used like this:

for index in 5>>>0 {
print(index)
}

// 4
// 3
// 2
// 1
// 0

- Check out [On C-Style For Loops Removed from Swift 3][1]

[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

Reply

#7
You can use reversed() method for easily reverse values.

var i:Int
for i in 1..10.reversed() {
print(i)
}

The reversed() method reverse the values.

Reply

#8
**In Swift 4 and latter**

let count = 50//For example
for i in (1...count).reversed() {
print(i)
}

Reply

#9
**Swift 4** onwards


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
Reply

#10
**Swift 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
}
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through