Listing 6.5 Classic for loop


#1

Hi all,

Stuck on Listing 6.5: when I type in the following code:

for var i = 1; i < 6; i+=1 {
myFirstInt += 1
print(myFirstInt)
}

it displays this error message:
Playground execution failed: error: LOOPS.playground:9:1: error: C-style for statement has been removed in Swift 3
for var i = 1; i < 6; i+=1 {
^ ~~~~ ~~~ ~~~~~~ ~~~~~~
in …<

Any help would be greatly appreciated!


#2

Don’t be scared. The error message is only saying that that syntax is no longer supported, and that you should use the new syntax, without telling you what it is.

For example.

Style 1:

for i in 1..<6 {
    print ("i = \(i)")
}

Style 2:

for i in stride (from:1, to:6, by:1) {
    print ("i = \(i)")
}

As you can see the second style is more flexible, which makes it possible to increment the value of the loop variable by any int value, not just by 1.


#3

Thank you for the help, ibex10!