Tag Archives: Swift

[Swift] create an array of a repeated range

Say you want to create an array like [1,2,3,1,2,3,1,2,3] etc. in Swift. I did some looking and couldn’t find a satisfactory answer that didn’t involve writing an extension to the Array class. But after playing with some code I managed to find this

let a = Array(repeating: [1,2,3], count: 3)

which creates a 2D array and then flattens it into a 1D using flatMap , probably not the most performant solution in the world but at least it’s terse 😀

Swift has an algorithm library which makes this task much more concise using the cycled algorithm
The following code accomplishes the same and the algo is lazy so it only creates the values needed but if you don’t give it a bound it will loop until the ends of time!

let cycles = [1,2,3].cycled(times: 3)

I learned about this and other cool functions from the swift-algorithms library from the Ray Wenderlich website