Multiple ways to create an array with incremented values in the swift example
This tutorial shows you multiple ways to create an array with incremented values or a range of values in Swift for example.
It is very useful to initialize increased values in Development to learn and test array methods.
How to create and initialize an array with incremented values?
There are multiple ways we can do this.
One way is Notation operator (…)
It contains a range of values with start and end and both are included.
For example, array(0…n) generates an array with values 0 and increments by 1 up to an equal number n.
Here is an example of creating an array initialized with a range of values.
// assign array with range of values incremented
let numbers = Array(0...10);
print(numbers)
// assign array type
let numbers1 = [Int](1...10)
print(numbers1)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Similarly, If you want to generate a range of values excluding the end value. Use ..<
operator.
The end value is excluded from the array.
let numbers = Array(1..<5);
print(numbers)
Output:
[1, 2, 3, 4]
The second way, using Iterate range of values with map and assign to the Array object
var numbers1 = (1...5).map { $0 }
print(numbers1)
Output:
[1, 2, 3, 4, 5]
Third way, using stride🔗 function that increments by given value.
func stride<T>(
from start: T,
to end: T,
by stride: T.Stride
) -> StrideTo<T> where T : Strideable
Here is an example from 0 to 100 incremented by 10
let floatNumbers = Array(stride(from: 0, through: 100, by: 10))
print(floatNumbers)
Output:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Initialize an array with float and double value incremented
Notation operator is used to and iterated using map values and assign the values to Float or Double, finally assign to an array.
Here is an example.
var numbers = (0..<5).map{ Float($0) }
print(numbers)
var numbers1 = (0..<5).map{ Double($0) }
print(numbers1)
Output:
[0.0, 1.0, 2.0, 3.0, 4.0]
[0.0, 1.0, 2.0, 3.0, 4.0]
Similarly, You can initialize float or double values with incremented by .1 as given below
let floatNumbers = Array(stride(from: 1.0, through: 2.0, by: 0.1))
print(doubles)
Output:
[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9000000000000001, 2.0]
Summary
In this tutorial, You learned a create and initialize an array with an incremented range of values using multiple ways.