Make NSNumberformatter().numberFromString return an optional

家住魔仙堡 提交于 2019-12-24 14:53:18

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/28599569/make-nsnumberformatter-numberfromstring-return-an-optional

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