Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an array of Doubles in Swift 4

Tags:

arrays

swift

I can initialize an array of Ints in Swift 4 as follows:

// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let intArray = Array(1...10)

If I specify the array as an array of Doubles like so:

let doubleArray1: [Double] = Array(1...100)

...the compiler says:

Cannot convert value of type 'Array' to specified type '[Double]'

If I try this:

let doubleArray1 = Array<Double>(1...100)

...the compiler says this...

Cannot invoke initializer for type 'Array' with an argument list of type '(CountableClosedRange)'

I got it to work using map, as follows:

// [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
let doubleArrayMap = Array(1...10).map{Double($0)}

Is there a "cleaner" way to quickly initialize an array of Doubles without using map in Swift?

like image 855
Adrian Avatar asked Mar 02 '18 15:03

Adrian


1 Answers

You can initialize an array from the sequence produced by stride():

let doubles = Array(stride(from: 1.0, through: 100.0, by: 1.0))

But keep aware of the restricted floating point precision: If the increment is not an integral value then rounding errors can accumulate. Mapping (and scaling) an integer range would then be the safer solution.

like image 91
Martin R Avatar answered Oct 27 '22 16:10

Martin R