Multiple Ways to create an Array filled with repeated values in the Swift example
- Create and initialize an array with Int and float value repeat multiple times using
repeating
andcount
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?
There are multiple ways we can do this to create an array.
- With the same value multiple times
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 a Float array with a 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 a Integer
, or Float
array with the same values
Let’s see an example to create an array, assigned with the same string for multiple values. repeating
is a value that is repeated in an array. count
: is a number of times or array fixed size.
// Generate an array with the 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.