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 Cat
s)
It there a simple command I can do, which does not use a loop?
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With