Decrement index in a loop after Swift C-style loops deprecated
Here is an easier (and more Swifty) approach.
for i in (0 ..< 5).reversed() {
print(i) // 4,3,2,1,0
}
let array = ["a", "b", "c", "d", "e"]
for element in array.reversed() {
print(element) // e,d,c,b,a
}
array.reversed().forEach { print($0) } // e,d,c,b,a
print(Array(array.reversed())) // e,d,c,b,a
How to use for in loop decrement condition in swift?
Use the stride() method:
for i in 10.stride(to: 5, by: -1) {
print ("Four multiplied by \(i) results in \(i*4)" )
}
This will increment through 10, 9, 8, 7, and 6. If you want 5 to be included, use through:
instead:
for i in 10.stride(through: 5, by: -1) {
print ("Four multiplied by \(i) results in \(i*4)" )
}
#warning: C-style for statement is deprecated and will be removed in a future version of Swift
Removing for init; comparison; increment {}
and also remove ++
and --
easily. and use Swift's pretty for-in loop
// WARNING: C-style for statement is deprecated and will be removed in a future version of Swift
for var i = 1; i <= 10; i += 1 {
print("I'm number \(i)")
}
Swift 2.2:
// new swift style works well
for i in 1...10 {
print("I'm number \(i)")
}
For decrement index
for index in 10.stride(to: 0, by: -1) {
print(index)
}
Or you can use reverse()
like
for index in (0 ..< 10).reverse() { ... }
for float type (there is no need to define any types to index)
for index in 0.stride(to: 0.6, by: 0.1) {
print(index) //0.0 ,0.1, 0.2,0.3,0.4,0.5
}
Swift 3.0:
From Swift3.0
, The stride(to:by:)
method on Strideable has been replaced with a free function, stride(from:to:by:)
for i in stride(from: 0, to: 10, by: 1){
print(i)
}
For decrement index in Swift 3.0
, you can use reversed()
for i in (0 ..< 5).reversed() {
print(i) // 4,3,2,1,0
}
Other then for each
and stride()
, you can use While Loops
var i = 0
while i < 10 {
i += 1
print(i)
}
Repeat-While Loop:
var a = 0
repeat {
a += 1
print(a)
} while a < 10
check out Control flows in The Swift Programming Language Guide
how to rewrite the following for loop in swift 3 syntax?
for i in stride(from: n-2, through: 0, by: -1) {
}
Swift range operator for i = mymax; i = 0 i--
It's easy to reverse the loop. User reversed
function.
Swift 3
let myMax = 20
for i in (1..<myMax).reversed() {
print(i)
}
You can also use stride
as @ZaidPathan said :
This question have all answers with all versions : How to iterate for loop in reverse order in swift?
What are the advantages Swift deprecates C-style for statement?
For details, see Swift Evolution - Remove C style for-loops
To quote the reasoning:
- Both
for-in
andstride
provide equivalent behavior using Swift-coherent approaches without being tied to legacy terminology.- There is a distinct expressive disadvantage in using for-loops compared to for-in in succinctness
for-loop
implementations do not lend themselves to use with collections and other core Swift types.- The
for-loop
encourages use of unary incrementors and decrementors, which will be soon removed from the language.- The semi-colon delimited declaration offers a steep learning curve from users arriving from non C-like languages
- If the for-loop did not exist, I doubt it would be considered for inclusion in Swift 3.
In summary: there are better ways (more expressive) than a C-style for-loop
to iterate in Swift.
Some examples:
for-in
over a range:
for i in 0 ..< 10 {
//iterate over 0..9
print("Index: \(i)")
}
for i in (0 ..< 10).reverse() {
//iterate over 9..0
print("Index: \(i)")
}
For arrays (and other sequences) we have many options (the following is not a complete list):
let array = ["item1", "item2", "item3"]
array.forEach {
// iterate over items
print("Item: \($0)")
}
array.reverse().forEach {
// iterate over items in reverse order
print("Item: \($0)")
}
array.enumerate().forEach {
// iterate over items with indices
print("Item: \($1) at index \($0)")
}
array.enumerate().reverse().forEach {
// iterate over items with indices in reverse order
print("Item: \($1) at index \($0)")
}
for index in array.indices {
// iterate using a list of indices
let item = array[index]
print("Item \(item) at index: \(index)")
}
Also note that if you are converting an array to another array, almost always you want to use array.filter
or array.map
or a combination of them.
For all Strideable
types we can use the stride
method to generate indices, for example:
for index in 10.stride(to: 30, by: 5) {
// 10, 15, 20, 25 (not 30)
print("Index: \(index)")
}
for index in 10.stride(through: 30, by: 5) {
// 10, 15, 20, 25, 30
print("Index: \(index)")
}
With arrays we can do:
for index in 0.stride(to: array.count, by: 2) {
// prints only every second item
let item = array[index]
print("Item \(item) at index: \(index)")
}
Converting a C-style for loop that uses division for the step to Swift 3
MartinR's solution is very generic and useful and should be part of your toolbox.
Another approach is to rephrase what you want: the powers of two from 7 down to 0.
for i in (0...7).reversed().map({ 1 << $0 }) {
print(i)
}
A concise way to not execute a loop now that C-Style for loops are going to be removed from Swift 3?
To do this in a way that works for n < 2, you can use the stride
method.
let startIndex = 2
let endIndex = n
for i in stride(from: startIndex, through: endIndex, by: 1) {
memo.append(memo[i-1] + memo[i-2])
}
Related Topics
Swift Lazy Instantiating Using Self
Why My Return Is Nil But If I Press the Url in Chrome/Safari, I Can Get Data
Printing a Variable Memory Address in Swift
How to Get Current Language Code With Swift
What Does "@Uiapplicationmain" Mean
What's the Simplest Way to Convert from a Single Character String to an Ascii Value in Swift
Prevent Dismissal of Uialertcontroller
How to Create Local Scopes in Swift
Swiftui Iterating Through Dictionary With Foreach
Get Terminal Output After a Command Swift
Decrement Index in a Loop After Swift C-Style Loops Deprecated
What Is the Meaning of the '#' Mark in Swift Language
Convert String to Url (Why Is Resulting Variable Nil)
Swift Closure Async Order of Execution
== Overload for Custom Class Is Not Always Called
Swift 2.0: 'Enumerate' Is Unavailable: Call the 'Enumerate()' Method on the Sequence