In Swift 5.8 we can develop a function that loops over an array, and return an array of elements at certain indexes. We can return every nth element this way.
With modulo division, we can test the indexes of an array. Calling enumerated()
on the array allows us to elegantly access indexes and values.
To begin, we introduce an everyNthElement
function. This version operates on a String
array, but it could be easily changed to use another element type.
String
array—this is where we will store the results as we encounter them.enumerated()
, and test all the indexes with modulo division.func everyNthElement(array: [String], n: Int) -> [String] { // Step 1: create result array. var result = [String]() // Step 2: loop over array, and if index is evenly divisible by n, append it. for (index, value) in array.enumerated() { if index % n == 0 { result.append(value) } } // Step 3: return result array. return result } // Use the function on this array. var test = [String](arrayLiteral: "a", "b", "c", "d", "e", "f", "g", "h", "i") var result = everyNthElement(array: test, n: 2) print(result) var result2 = everyNthElement(array: test, n: 3) print(result2)["a", "c", "e", "g", "i"] ["a", "d", "g"]
It is easy to see that the function returns the correct results, just by checking the input array and the output. With an argument of 2, it skips every other element.
With modulo division, we can test for elements in an array that are a certain distance apart. And by calling append()
on an empty array, we can place these elements in a new collection.