Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do a i+=2 for-loop in Swift? [duplicate]

Tags:

for-loop

swift

for example, a Java for-loop:

for(int i=0; i<5; i+=1){
   //
}

convert to Swift

for index in 0..<5 {
}

but what if i+=2?

I'm new to Swift.. Maybe it's a stupid question, but will be appreciate if you answer it, thx! :-)

like image 722
voicebeer Avatar asked Nov 29 '17 09:11

voicebeer


People also ask

What is a for loop in Swift?

For loop usage in Swift. The for loop might be the most well-known method for iteration over all programming languages. It’s also known as the for-in loop in Swift. This example iterates over an array of cities, also known as a collection in Swift.

How to iterate over a range in Swift?

In Swift, we can use for loop to iterate over a range. For example, In the above example, we have used the for-in loop to iterate over a range from 1 to 3. The value of i is set to 1 and it is updated to the next number of the range on each iteration. This process continues until 3 is reached. 1 is printed. i is increased to 2.

What is the use of for-in loop in C?

For-in loops are used to run a set of tasks for a certain number of times. These loops iterate over any sequences such as items in an array, range, or characters in a string. We also use for-in loop to do some repetitive processes for a fixed amount of time.

What is the difference between for-in loop and if statement?

We have collections like sets, arrays, dictionaries, so we can iterate their items using a for-in loop, which means it is used to iterate over any sequence. for-in loop and if statement is quite similar. In an if statement, the condition is used to execute a block of statements only when the condition is satisfied.


3 Answers

Check this

for index in stride(from: 0, to: 5, by: 2){
    print(index)
}
like image 95
Uma Madhavi Avatar answered Oct 14 '22 06:10

Uma Madhavi


You can use this way as well.

var first = 0
var last = 10
var add = 2
for i in sequence(first: first, next: { $0 + add })
.prefix(while: { $0 <= last }) {
    print(i)

} 

Output will be: 0,2,4,6,8,10

like image 33
Muhammad Shauket Avatar answered Oct 14 '22 05:10

Muhammad Shauket


In case if your for loop was doing something more complex than adding constant value to index each iteration you may use something like that:

Assuming you have this for loop:

for(index = initial; condition(index); mutation(index)){
   //
}

Where

  • initial — initial value constant of type T
  • condition — function (T) -> Bool, that checks if loop should end
  • mutation — function (T) -> T, that changes index value each iteration

Then it will be:

for index in sequence(first: initial, next: { current in
    let next = mutation(current)
    return condition(next) ? next : nil
}) {
   //
}
like image 1
user28434'mstep Avatar answered Oct 14 '22 07:10

user28434'mstep