In my project contain this following line of code. But I always get the error. I am using Xcode 7.2 and iOS 9.
let image: UIImage = UIImage(CGImage:imageRef, scale:originalImage.scale, orientation:originalImage.imageOrientation)!
In my project contain this following line of code. But I always get the error. I am using Xcode 7.2 and iOS 9.
let image: UIImage = UIImage(CGImage:imageRef, scale:originalImage.scale, orientation:originalImage.imageOrientation)!
Remove the !
The result of that method isn't optional - you don't need to unwrap it.
NB You don't need the : UIImage
from the variable - Swift will infer it's type for you.
EDIT: What if imageRef
is optional (from @chewie's comment)?
You have a few options.
1 Use if let
:
if let imageRef = imageRef {
let image = UIImage(CGImage: imageRef, scale: originalImage.scale, orientation: originalImage.imageOrientation)
// Do something with image here
}
2 Use 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 Use map
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 :)
The choice of which to use is yours, but here's my rule of thumb.
If what you need to do requires an image, use guard
and abort early if you don't have one. This generally makes your code easier to read and understand.
If what you need to do can be done without an image, use if let
or map
. if let
is useful if you just want to maybe do something and then carry on. map
is useful if you need to pass your UIImage?
around and use it later.