Imran Imran - 7 months ago 11
Swift Question

Repeating array in Swift

In Python I can create a repeating list like this:

>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]


Is there a concise way to do this in Swift?

The best I can do is:

1> var r = [Int]()
r: [Int] = 0 values
2> for i in 1...3 {
3. r += [1,2,3]
4. }
5> print(r)
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Answer

You can create a 2D array and then use flatMap to turn it into a 1D array:

let array = Array(count: 3, repeatedValue: [1,2,3]).flatMap{$0}