This tutorial shows you multiple ways to create an array with the same values in an array of Swift for example.

It is very useful to initialize repeated values in Development to learn and test array methods.

How to create and initialize an array with the same values?

There are multiple ways we can do this.

It uses repeating and count syntax to create a value.

repeating is a repeating value in an array. count is multiple times to repeat in the array.

Here is an example of creating an array same value multiple times.

// Generate an array with zero value repeated 5 times
var numbers = Array(repeating: 0, count:5)
print(numbers)
// Generate an Int array with zero value repeated 5 times
var numbers1 = [Int](repeating: 0, count:5)
print(numbers1)
// Generate an Float array with 1.0 value repeated 5 times
var numbers2 = [Float](repeating: 1, count:5)
print(numbers2)

Output:

[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1.0, 1.0, 1.0, 1.0, 1.0]

The above example generates an Integer, Float array with the same values

Let’s see an example to create an array, assigned with the same string for multiple values.

// Generate an array with same string value repeated 5 times
var strArray = Array(repeating: "one", count:5)
print(strArray)

Output:

["one", "one", "one", "one", "one"]

Summary

In this tutorial, You learned a create and initialize an array with the same or repeated values using multiple ways.