Swift 3 Convert Double to String

rahmikg picture rahmikg · Nov 5, 2016 · Viewed 11.7k times · Source

I keep getting this error "Initializer for conditional binding must have Optional type, not 'Double'". I am trying to display some core data values and this one is a double. Ive tried to work around it the same way I had to do to store the values when converting it.

heres the code that gives me the error:

func displayStats() {



        // display other attributes if they have values
        if let servingSize  = mealstats.serving {
            servingsLabel.text = servingSize

        }

Answer

Abhra Dasgupta picture Abhra Dasgupta · Nov 6, 2016

mealstats.serving is most probably of type "Double" and not "Double?"
Since it is not optional it cannot be unwrapped. The right way to use it would be

func displayStats() {
    // display other attributes if they have values
    servingsLabel.text = "\(mealstats.serving)"
}