1

I have an array of 100 items. I want to iterate it with specific steps, 2n, 3n, 4n etc. For example, if n = 3, i want to iterate 3,6,9,12 elements of array.

How to achieve that? Thanks.

Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

2 Answers2

8

In Swift you can do this with help of stride.

let n = 3

for index in stride(from: 0, through: 100, by: n) {
    print(index)
}

Output of the indexes:

0
3
6
9
12
15
18
21
24
27
30
33
36
39
42
...
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
  • thanks, but i also did achieve that with that : for i in 0...tmp.count { if let numb : Number = tmp[p*i]{ numb.isDeleted = true } } – Evgeniy Kleban Jun 19 '17 at 08:46
  • yes but for the case that you describe it is more suitable to use syntax that I describe without usage of the own calculations. – Oleg Gordiichuk Jun 19 '17 at 08:48
1

I dont know swift but by the look of it from the basic swift loops this should do exactly what you want :

var i = 1
var n = 2
while i <= 100 {
    print(i)
    i = i + n
}
ebby94
  • 3,131
  • 2
  • 23
  • 31
Aakash Uniyal
  • 1,519
  • 4
  • 17
  • 32