[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)
    .flatMap{$0}

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 😀

UPDATE:
Swift has an algorithm library which makes this task much more concise using the cycled algorithm
https://github.com/apple/swift-algorithms
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
https://www.raywenderlich.com/18517868-swift-algorithms-getting-started