Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a Swift for-in loop with a step?

Tags:

swift

With the removal of the traditional C-style for-loop in Swift 3.0, how can I do the following?

for (i = 1; i < max; i+=2) {     // Do something } 

In Python, the for-in control flow statement has an optional step value:

for i in range(1, max, 2):     # Do something 

But the Swift range operator appears to have no equivalent:

for i in 1..<max {     // Do something } 
like image 273
Adam S Avatar asked Feb 22 '16 15:02

Adam S


People also ask

How do you run a for loop in Swift?

for Loop with where Clause In Swift, we can also add a where clause with for-in loop. It is used to implement filters in the loop. That is, if the condition in where clause returns true , the loop is executed. In the above example, we have used a for-in loop to access each elements of languages .

What is stride function in Swift?

Swift has a helpful stride() , which lets you move from one value to another using any increment – and even lets you specify whether the upper bound is exclusive or inclusive.

For what purpose the stride from to by function is used?

You can use this function to stride over values of any type that conforms to the Strideable protocol, such as integers or floating-point types. Starting with start , each successive value of the sequence adds stride until the next value would be equal to or beyond end .


1 Answers

The Swift synonym for a "step" is "stride" - the Strideable protocol in fact, implemented by many common numerical types.

The equivalent of (i = 1; i < max; i+=2) is:

for i in stride(from: 1, to: max, by: 2) {     // Do something } 

Alternatively, to get the equivalent of i<=max, use the through variant:

for i in stride(from: 1, through: max, by: 2) {     // Do something } 

Note that stride returns a StrideTo/StrideThrough, which conforms to Sequence, so anything you can do with a sequence, you can do with the result of a call to stride (ie map, forEach, filter, etc). For example:

stride(from: 1, to: max, by: 2).forEach { i in     // Do something } 
like image 102
Adam S Avatar answered Sep 23 '22 06:09

Adam S