【发布时间】:2017-02-01 07:21:16
【问题描述】:
我在一个 xcode 8 项目中有以下 swift 3 代码:
if pictureImg.image == nil {
print("image nil")
}
if pictureImg.image != nil {
print("image not nil")
}
if pictureImg.image != nil {
imageData = UIImageJPEGRepresentation(pictureImg.image!, 0.5)!
}
在运行时,我在控制台中得到了一个特殊的结果:
image not nil
fatal error: unexpectedly found nil while unwrapping an Optional value
所以看起来我的图片Img.image 实际上是 nil 尽管我之前的 相同 if 声明另有说明。检查 UIImageJPEGRepresentation 是否为 nil 也会导致相同的错误:
if UIImageJPEGRepresentation(pictureImg.img!, 0.5) == nil { *code* }
确认问题肯定与pictureImg.image有关,或者看起来是这样。
此代码是否存在直接/明显的问题,或者是否需要说明有关该项目的更多信息?
【问题讨论】:
-
您是否在检查
UIImageJPEGRepresentation是否返回nil?你在那里强制解开返回值。此外,您应该使用if let语句而不是检查nil。 -
永远,永远不要使用!解开可选的罪 Swift。有很多不错的方法可以做到这一点。这是用大事来粉碎它的方法。
-
@Fogmeister,“可选罪 Swift”!?!现在这是一个有趣的错字!