Reputation: 328
maybe question is so silly but i am new in iOS
how can I convert optional to non-optional data array
[Double?] is not convertible to [Double]
Here is line with error
let massive = [dictionary[j]![one]?.doubleValue] as [Double]
I am converting to [Double] because i am using it here
let dataEntry = BarChartDataEntry(values: massive, xIndex: c)
And it throws error
Cannot invoke initializer for type 'BarChartDataEntry' with an argument list of type '(values: [Double?], xIndex: Int)'
contructor of class BarChartDataEntry is like that
public init(values: [Double], xIndex: Int)
Upvotes: 1
Views: 646
Reputation: 19954
[Double?] is wrapped, you have to unwrap it in order to use it as a [Double]. To better understand, take a look at what your Doubles are wrapped with:
enum Optional<T> {
case None // has no value
case Some(T) // has some value
}
So you need to unwrap your optionals in order to use them as non-optional [Double].
One option, is that you can perform a flatMap
operation on your optional array which will convert your [Double?] to a [Double]. Bear in mind that flatMap will copy your array and replace it, so if you're performing a flatMap on a very large array you might run into issues.
Here's a playground ready example:
var dubs : [Double?] = [1.2,1.4]
print(dubs) // [{Some 1.2}, {Some 1.4}]
var newDubs = dubs.flatMap { dub in
return dub
}
print(newDubs) // [1.2, 1.4]
Upvotes: 2
Reputation:
It depends on what your value for your double is. In this case, you must be sure that it has a decimal point, and is not 0.0. In which case, you can put your code as
//your code
... = Double[...]
It should resolve. Else, please provide some code so I can suggest a way to resolve. Hope this works for you :)
Upvotes: 0