Initializing an array of Doubles in Swift 4

Adrian

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?

Martin R

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related