Reputation: 21
I'm trying to send images to core data via a name the user types in for images already in the assets folder. Then the program supposed to take the image and display it for the user in my table view controller in a cell. However whenever I run my code with these two lines:
self.animeImage.image = UIImage(data: self.animeDetail.aImage as! Data)
and
cell.cellAnimeImage?.image = UIImage(data:cellAnime.aImage as! Data)
I get another error found nil while unwrapping an optional value. I'm not sure why this is happening since I'm trying put my images into two image views with these two separate pieces of code using outlets. I believe that outlets are already implicitly unwrapped optional. So I'm not sure why I'm having issues. Any explanations would be greatly appreciated.
Upvotes: 0
Views: 2578
Reputation: 96
The optionValue is a structure,
enum optionValue<T> : LogicValue, Reflectable {
case None
case Some(T)
...
}
as! is coercive type conversion,u can't turn a structure into a data.
unwrapped optional:
let object = optionValue!
let object = optionValue ?? "anyDefaultValue"
If Some(T) doesn't have a value, it will cause a crash when u use ! to unwrapped the optionalValue,u can give a default value like this: optionValue ?? "anyDefaultValue" to avoid crash when there is no value
Upvotes: 0
Reputation: 299643
By the looks of it, aImage
is of type Data?
. If you are absolutely certain that it really has a value, you can use !
here (and should not use as!
):
self.animeImage.image = UIImage(data: self.animeDetail.aImage!)
However, it is generally better to check rather than assuming that aImage
is not nil
. As you note, sometimes it's nil
.
if let imageData = self.animeDetail.aImage {
self.animeImage.image = UIImage(data: imageData)
}
As a rule, you should avoid use of !
except in fairly special cases.
Upvotes: 5