Home
Swift
Array Every Nth Element
Updated Aug 9, 2023
Dot Net Perls
Nth element. 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.
Step 1 We create an empty String array—this is where we will store the results as we encounter them.
Step 2 We loop over the input array with enumerated(), and test all the indexes with modulo division.
Step 3 We return the result array, which now is populated with every nth element from the input array.
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"]
Results. 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.
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 9, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen