user3395936 user3395936 - 7 months ago 170
Swift Question

Cannot convert value of type '[Double]' to expected argument type 'Double'

This might be a very stupid question but I can't seem to find an answer.
I have this piece of code which converts an input of numbers into doubles :

var array: [Double]! = []
data = try String(contentsOfFile: localFilePath as String,
encoding: NSASCIIStringEncoding)

let myStrings = data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())

var trial = myStrings[0].componentsSeparatedByString(",").flatMap{Double($0.stringByTrimmingCharactersInSet(.whitespaceCharacterSet()))}

array.append(trial)


So for example if my file has these numbers
1.2,3.4,5.6
then the output will be
[1.2,3.4,5.6]
and so on.
I get the above error when I try to append my array, what is the right way of casting this? Thank you.

Answer

What you are looking for is appendContentsOf, not append.

flatMap returns a [Double], and you want to append the contents of that array to array.

Merely change

array.append(trial)

to:

array.appendContentsOf(trial)
Comments