致命错误:解开可选值时意外发现nil-Stanford Calculator [英] fatal error: unexpectedly found nil while unwrapping an Optional value - Stanford Calculator

查看:98
本文介绍了致命错误:解开可选值时意外发现nil-Stanford Calculator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ItanesU上观看斯坦福Swift的讲师,但在理解上有些困难.

I'm watching the Stanford Swift lecturers on ItunesU and have some trouble in understanding.

讲师正在一次将字符串转换为Double类型. 他这样做如下:

The lecturer is typecasting a String to a Double at one point. He did it as follows:

return NSNumberFormatter().numberFromString(display.text!)!.doubleValue

display.text是一个UILabel 无论如何,当我这样做时,我的应用程序崩溃了,并且出现了以下错误:

display.text is a UILabel Anyhow, when I'm doing it like this my app crashes and I get the following error:

致命错误:解开可选值时意外发现nil

fatal error: unexpectedly found nil while unwrapping an Optional value

当我像这样打字字符串时:

When I typecast the String like this:

(display.text! as NSString).doubleValue

它工作正常.

我知道任何地方都必须有一个可选的var,但我并不是要说这是什么地方.

I know there must be an optional var anywhere but I'm not that into it to say what is wrong at this point.

推荐答案

问题是您的display.text文本中没有有效数字.因此它将返回nil.

The issue is your display.text doesn't have a valid number in it's text. So it'll return nil.

因此您的表情将变为:

return nil!.doubleValue

它肯定会崩溃.

对于将String转换为double的方法,您的第二种方法更合适.表示使用:

For converting a String to double your second approach is more suitable. Means using:

(display.text! as NSString).doubleValue

是这种情况下的一种更好的方法.

is a better approach for this case.

参考文献: NSNumberFormatter类参考

- numberFromString:

返回通过解析给定字符串创建的NSNumber对象.

Returns an NSNumber object created by parsing a given string.

声明

快速

func numberFromString(_ string: String) -> NSNumber?

Objective-C

- (NSNumber *)numberFromString:(NSString *)string

参数

字符串

一个NSString对象,该对象经过解析以生成返回的数字 对象.

An NSString object that is parsed to generate the returned number object.

返回值

通过使用接收方的字符串解析字符串创建的NSNumber对象 格式.如果所传递的字符串中没有数字,则返回nil.

An NSNumber object created by parsing string using the receiver’s format. Returns nil if there are no numbers in the passed string.

讨论

字符串中的任何前导空格都将被忽略.例如,字符串 5"和"5"的处理方式相同.

Any leading spaces in a string are ignored. For example, the strings " 5" and "5" are handled in the same way.

这篇关于致命错误:解开可选值时意外发现nil-Stanford Calculator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆