意外地发现零,同时展开可选值

在我的应用程序中,我正在检查一个post是否有图片。

为此,我正在使用:

if pictures[string]? != nil { if var image: NSData? = pictures[string]? { imageView.image = UIImage(data: image!) } } 

但是,它仍然出现错误:

致命错误:意外地发现零,而解包一个可选值。

我相信这是一个很容易解决的问题,但是我对此很新颖 – 我做错了什么?

试试这样做:

 if let imageData = pictures[string] { if let image = UIImage(data: imageData) { imageView.image = image } } 

假设这个string是一个有效的键。

你正在处理可选项,所以在使用之前有条件地解开每个返回对象。

强制展开是非常危险的,只有当您确定可选项包含值时才能使用。 您的imageData可能无法以正确的格式创build图像,但无论如何您都会强制展开图像。 这在Objective-C中是可以的,因为它只是意味着nil对象被传递。 斯威夫特并不那么宽容。

当你忘记包装可选的值时,这是快速的问题

imageView?.image = UIImage(data: image!)replaceline imageView?.image = UIImage(data: image!)

我遇到了这个代码的同样的问题

 if(!placeholderColor.isEqual(nil)) { self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName : placeholderColor]) } 

并由此解决

 if let placeColor = placeholderColor { self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName : placeColor]) }