7

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?

0

2 Answers 2

26

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"))
Sign up to request clarification or add additional context in comments.

Comments

7

The array initilizer Array(repeating:count:) can be used to create an array with repeated values:

var myArray = ["Swan", "Dog"]
myArray += Array(repeating: "Cat", count: 10)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.