问题描述
我是新手.只是想知道如何将下面的代码转换为可选代码.
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
}
}
这是来自斯坦福计算器讲座系列.讲师没有显示如何使其可选.我的理解是,当displayValue中有一个不能转换为Double的字符串(例如"Error")时,应用程序崩溃.问题在于displayValue需要显示可以在不同时间转换为Double的字符串.
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.
谢谢
推荐答案
无需使其返回可选值.您可以使用nil合并运算符在nil情况下返回0,如下所示:
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
这篇关于使NSNumberformatter().numberFromString返回可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!