2015-05-13 98 views
0

爲什麼這個變量爲「無」即使我檢查是否self.photoImageView.image != nil,在倒數第二行嘗試applyBlurEffect時仍然出現fatal error: unexpectedly found nil while unwrapping an Optional value錯誤。即使我有一個「if」語句來檢查它不是

你知道如何調和嗎?

if (output?.getAccel() == true){ 
     if (output?.getImage() != nil){ 
      if (self.photoImageView.image != nil){ 
       println(photoImageView.image) 
       var blurredImage = self.applyBlurEffect(self.photoImageView.image!) 
       self.photoImageView.image = blurredImage 
      } 

對於上下文,我有一個photoImageView,並且當一個「加速度計按鈕」被插入該photoImageView,這個函數使用圖像,模糊它,並且更新圖像作爲模糊的圖像。

此外,當我打印photoImageView.image,它返回 Optional(<UIImage: 0x174087d50> size {1340, 1020} orientation 0 scale 1.000000)。其中可能存在這個問題,但我需要一點幫助來解決它。

+1

我不明白爲什麼這不起作用。我認爲這個問題與你在applyBlurEffect中做的事情有關,並不是因爲展開圖像給你零。 – rdelmar

回答

2

在Swift中,您必須使用可選綁定以確保可選項不爲零。在這種情況下,你應該做這樣的事情:

if let image = self.photoImageView.image { 
    //image is set properly, you can go ahead 
} else { 
    //your image is nil 
} 

這是斯威夫特一個非常重要的概念,所以你可以閱讀更多here

UPDATE:作爲@rdelmar指出,可選結合不是強制性這裏,檢查nil也應該夠了。我個人更喜歡使用可選綁定。其好處之一是multiple optional binding而不是檢查所有可選零件:

if let constantName = someOptional, anotherConstantName = someOtherOptional { 
    statements 
} 
+0

感謝這個,修復它。 –

+4

這是不正確的。你不*有*使用可選綁定,但它是一個很好的使用模式。在if語句中檢查可選的等於nil也應該起作用。 – rdelmar

相關問題