I need to create array with repeating elements (not single value)

I want to create an array like this:

[1, 2, 3, 1, 2, 3, 1, 2, 3, so on ]

So I added this:

extension Array {
    init(repeating: [Element], count: Int) {
        self.init()
        self.reserveCapacity(repeating.count * count)
        for _ in 1...count {
            self.append(contentsOf: repeating)
        }
    }
}

so I can create my array:

Array.init(repeating: [1, 2, 3], count: 35)

Did I do it right? Or there is better way?

You could leverage flatMap on Array:

Array(repeating: [1,2,3], count: 10).flatMap { $0 }

gives you [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3].

The documentation for Array.flatMap actually has pretty good documentation of what flatMap does with Arrays (concatenation).

As the docs point out, you can also use

Array(Array(repeating: [1,2,3], count: 10).joined())

which is probably a better and more readable way of achieving what you're looking for.

1 Like

Does it need to be an Array specifically?

Because if you just need a sequence that generates those values, you can do so without allocating memory:

let numbers = repeatElement(1..<4, count: 35).lazy.flatMap{ $0 }

If it must be an Array, you can omit the lazy:

let numbers = repeatElement(1..<4, count: (35).flatMap{ $0 }

I need it for SwiftUI Gradient.init(colors: [Color]).

I did not know about repeatElement(). Learn a new thing :slight_smile: Swift can be so expressive, if only I know more of its basic functions elementals building blocks. So much to learn.

Thanks!