Conversion of entire array from int to double in order to do some aritmetic operations

不羁的心 提交于 2019-12-07 18:04:27

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 Ints 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!