问题
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