【问题标题】:unexpectedly found nil while unwrapping an Optional value DESPITE checking [duplicate]在展开可选值时意外发现 nil 尽管检查 [重复]
【发布时间】: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”!?!现在这是一个有趣的错字!

标签: ios swift optional


【解决方案1】:

我想UIImageJPEGRepresentation(pictureImg.image!, 0.5)! 返回零。检查苹果文档。 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) {
     ...
}

【讨论】:

  • 请投票结束问题,然后重复:UIImageJPEGRepresentation returns nil
  • 如果 let 语句,您可以将这些链接到 1 中。如果您只对特定组合感兴趣,我认为它看起来更整洁。
  • 像魅力一样工作!如果这个问题很愚蠢,我很抱歉,我是这个游戏的新手,我真的很感谢你们能帮助我们这些白痴!
猜你喜欢
  • 2014-12-27
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
相关资源
最近更新 更多