Use Array()
with stride(from:through:by:)
:
let arr = Array(stride(from: 0, through: 5, by: 0.5))
print(arr)
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]
If your min
and max
values truly are Int
, then you'll need to convert them to Double
:
let min = 0
let max = 5
let step = 0.5
let arr = Array(stride(from: Double(min), through: Double(max), by: step))
Warning:
Due to the nature of floating point math, this can possibly lead to unexpected results if the step or endpoints are not precisely representable as binary floating point numbers.
@MartinR gave an example:
let arr = Array(stride(from: 0, through: 0.7, by: 0.1))
print(arr)
[0.0, 0.10000000000000001, 0.20000000000000001, 0.30000000000000004, 0.40000000000000002, 0.5, 0.60000000000000009]
The endpoint 0.7
was excluded because the value was slightly beyond it.
You might also want to consider using map
to generate your array:
// create array of 0 to 0.7 with step 0.1
let arr2 = (0...7).map { Double($0) / 10 }
That will guarantee that you capture the endpoint 0.7
(well, a close approximation of it).
So, for your original example:
// create an array from 0 to 5 with step 0.5
let arr = (0...10).map { Double($0) / 2 }