Search code examples
calculatoroption-typensnumberformatter

Make NSNumberformatter().numberFromString return an optional


I'm pretty new to swift. Just wanted to know how to convert the code below to be an optional.

var displayValue:  Double {
    get {
        return NSNumberFormatter().numberFromString(display.text! as NSString)!.doubleValue
         }
    set {
        display.text = "\(newValue)"
        userIsInTheMiddleOfTypeingANumber = false
    }
}

this is from the stanford calculator lecture series. The lecturer didn't show how to make it optional. My understanding is that when there is a string in displayValue that can't be converted to a Double (like "Error") the app crashes. The problem is displayValue needs to show strings that can and can't be converted to Double at different times.

I know similar questions have been asked before but I can't find a clear answer.

Thanks


Solution

  • No need to make it return an optional. You can use the nil coalescing operator to return 0 in case of nil as follow:

    return (NSNumberFormatter().numberFromString(display.text) as? Double) ?? 0