I have this bit of code:
var arrayIntegers : [Int] = []
arrayIntegers += 0...33
var arrayDecimal : [Int] = []
arrayDecimal += 0...999
The problem is I can´t convert the values of both arrays to Double. What I want to do is to get a new array (called arrayDoubleComposed) with composite values, taking a value of arrayIntegers as the integer part and then taking another value of arrayDecimal as the floating part.
When I try to typecast this:
var arrayDoubleComposed : [Double] = []
arrayDoubleComposed = Double (arrayIntegers[] + (arrayDecimal[])/1000)
I´ve got an error. The same if I suppress the [].
I´m a little bit newcomer, I know...
Converting one kind of array into another is a job for map
, which applies a function to each element of an array, returning the results as a new array of the type that function returns. In this case, you want a function that converts the Int
s to a Double
.
Try something like this:
let integers = Array(0...33)
let fractions = Array(0...999)
let arrayDoubleComposed = map(Zip2(integers, fractions)) {
(i, f) in
Double(i) + Double(f)/1_000
}
Zip2
takes two sequences and pairs them up – first elements together, second elements together etc. Then this passes that into map
which combines the two elements.
(note also you can just initialize the arrays from the ranges rather than declaring them then adding the values)
It’s not clear what you mean to do, as the integer and fractional arrays are going to be different length. The way Zip2
handles this is to stop when the first sequence runs out, but this may not be what you want.
P.S. casts like the one you tried, which convert the contents of an array en-mass, only work in special cases when converting from Objective-C types to native Swift types, when the Swift compiler sprinkles some magic.