2014-10-31 112 views
8

在我的应用程序中,我检查是否有帖子有图片。意外地发现零,同时展开可选值

对于这个我使用:

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

但是,它仍然想出了错误:

fatal error: unexpectedly found nil while unwrapping an Optional value.

我敢肯定,这是一些容易解决,但我很新的这 - 我做错了什么?

+0

可能的重复o f [什么是“致命错误:意外地发现零,而解包可选值”是什么意思?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping -an-optional-valu) – Hamish 2016-05-16 12:33:29

回答

14

尝试做这种方式:

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

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

您正在处理可选项,因此在使用它之前有条件地解开每个返回对象。

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

+0

谢谢:)现在工作! – 2014-10-31 13:29:13

1

这是迅速的,当你忘了包可选值

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

0

我用这个代码

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

面临着同样的问题,更换线路imageView.image = UIImage(data: image!) 并以此解决的问题

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