删除!
该方法的结果不是可选的 - 你不需要解开它。
NB 你不需要变量中的: UIImage - Swift 会为你推断它的类型。
编辑:如果imageRef 是可选的(来自@chewie 的评论)怎么办?
您有几个选择。
1 使用if let:
if let imageRef = imageRef {
let image = UIImage(CGImage: imageRef, scale: originalImage.scale, orientation: originalImage.imageOrientation)
// Do something with image here
}
2 使用guard
guard let imageRef = imageRef else {
print("Oops, no imageRef - aborting")
return
}
// Do something with image here
let image = UIImage(CGImage: imageRef, scale: originalImage.scale, orientation: originalImage.imageOrientation)
3 使用地图
let image = imageRef.map {
UIImage(CGImage: $0, scale: originalImage.scale, orientation: originalImage.imageOrientation)
}
// Do something with image here, remembering that it's
// optional this time :)
使用哪个是您的选择,但这是我的经验法则。
如果您需要执行的操作需要一张图片,请使用guard,如果您没有图片,请提前中止。这通常会使您的代码更易于阅读和理解。
如果您需要做的事情可以在没有图像的情况下完成,请使用if let 或map。 if let 如果您只想做某事然后继续,这很有用。如果您需要传递您的 UIImage? 并在以后使用它,map 非常有用。