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! :-)
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.
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.
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.
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.
Check this
for index in stride(from: 0, to: 5, by: 2){
print(index)
}
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
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 endmutation
— function (T) -> T
, that changes index value each iterationThen it will be:
for index in sequence(first: initial, next: { current in
let next = mutation(current)
return condition(next) ? next : nil
}) {
//
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With