-1

am new in swift I tried to make loop like this

for var z = 0 ; z <= 25 ; z = z + 5 {

print (z)
}

put it gives me this error

Loop.playground:5:1: error: C-style for statement has been removed in Swift 3

how can I solve it?

zainab
  • 3
  • 1

1 Answers1

0

You can use the where clause!

for z in 0...25 where z % 5 == 0 {
    print(z)
}

It basically filters out z values and it only leaves the z values that are divisible by 5, which is what you want.

This is wayyyy more swifty than the C-style for loop.

Another way to do this is with stride:

for i in stride(from: 0, through: 25, by: 5) {
    print(i)
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 1
    The first version may look "Swifty" but is *very ineffective.* `z` is incremented in steps of one, and an additional `%` operation is needed for each value to determine if the body should be executed or not. `stride()` – as in the linked-to duplicate – is a better solution. – Martin R Oct 31 '16 at 08:07
  • thank you for your help, it works well but this is if I want to increase the number by 5, what if I want to decreases the number? for example from 10 to 0 ? – zainab Nov 01 '16 at 05:57
  • @zainab simple, stride from 10 through 0 by -1! – Sweeper Nov 01 '16 at 06:43