Create a Circular Array with the Modulo Operator

If you need to continue looping over an array after you’ve reached the end, you can use the modulo operator to start the index back at 0.

For example:

let array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
let array2 = [1, 2, 3] // we want this array to loop around endlessly
var pointer = 0
for i in array1 {
    print(“array1 item: \(i)”)
    print(“array2 item: \(array2[pointer])”)
    print(“——————“)
    pointer = (pointer + 1) % array2.count
}

This will iterate over array1 once and continuously loop over array2, starting the pointer at 0 when it reaches the end.

This should print out:

array1 item: 1
array2 item: 1
-----------------
array1 item: 2
array2 item: 2
-----------------
array1 item: 3
array2 item: 3
-----------------
array1 item: 4
array2 item: 1
-----------------
array1 item: 5
array2 item: 2
-----------------
array1 item: 6
array2 item: 3
-----------------
array1 item: 7
array2 item: 1
-----------------
array1 item: 8
array2 item: 2
-----------------
array1 item: 9
array2 item: 3
-----------------
array1 item: 10
array2 item: 1
-----------------
array1 item: 11
array2 item: 2
-----------------
array1 item: 12
array2 item: 3
-----------------
array1 item: 13
array2 item: 1
-----------------
array1 item: 14
array2 item: 2
-----------------
array1 item: 15
array2 item: 3
-----------------
array1 item: 16
array2 item: 1
-----------------
array1 item: 17
array2 item: 2
-----------------
array1 item: 18
array2 item: 3
-----------------
array1 item: 19
array2 item: 1
-----------------
array1 item: 20
array2 item: 2
-----------------

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.