Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple identical elements to array in swift

Tags:

arrays

ios

swift

How would I add multiple identical elements to an array?

For instance, if the array was:

["Swan", "Dog"]

and I wanted to turn it into:

["Swan", "Dog", "Cat", "Cat", "Cat", "Cat", "Cat", "Cat", "Cat", "Cat", "Cat", "Cat"]

(adding 10 Cats)

It there a simple command I can do, which does not use a loop?

like image 215
cannyboy Avatar asked Oct 27 '16 09:10

cannyboy


1 Answers

In Swift 3 you can use repeatElement() which creates a collection containing the specified number of the given element:

var array = ["Swan", "Dog"]
array.append(contentsOf: repeatElement("Cat", count: 10))

In Swift 2 this would be:

var array = ["Swan", "Dog"]
array.appendContentsOf(Repeat(count: 10, repeatedValue: "cat"))
like image 188
Martin R Avatar answered Oct 04 '22 01:10

Martin R