我在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
所以看来我的pictureImg.image实际上是nil 尽管我之前的相同的 if语句另有说法。检查UIImageJPEGRepresentation是否为零也会导致相同的错误:
if UIImageJPEGRepresentation(pictureImg.img!, 0.5) == nil { *code* }
确认问题肯定与pictureImg.image有关,或者似乎是这样。
此代码是否存在直接/明显的问题,还是需要说明有关该项目的更多信息?
答案 0 :(得分:3)
我认为UIImageJPEGRepresentation(pictureImg.image!, 0.5)!
返回nil。查看Apple文档。 https://developer.apple.com/reference/uikit/1624115-uiimagejpegrepresentation
做这样的事情:
if let image = pictureImg.image {
if let imageRepresentation = UIImageJPEGRepresentation(image, 0.5) {
...
}
}
这样你就不会有任何问题。
或者您可以将它们链接为@Emptyless建议
if let image = pictureImg.image, let imageRepresentation = UIImageJPEGRepresentation(image, 0.5) {
...
}