In my app I am checking to see whether a post has a picture or not.
For this I am using:
if pictures[string]? != nil {
if var image: NSData? = pictures[string]? {
imageView.image = UIImage(data: image!)
}
}
However, it still comes up with the error:
fatal error: unexpectedly found nil while unwrapping an Optional value.
I'm sure it is something easy to fix but I am quite new to this - what am I doing wrong?
99% of the time the above error is caused by a force-unwrapped optional that is nil. You can fix it by avoiding it becomes nil, which is sometimes not possible, so then you use optional binding or optional chaining. Avoid using implicitly unwrapped optionals when you can, unless you have a specific need to use it.
It's called implicitly unwrapped since Swift force unwraps it every time. The drawback of this is same as forced unwrapping - if the value is nil when accessing, it leads to a fatal error. Similar to optionals, optional binding and optional chaining can also be used for implicitly unwrapped optionals.
It means that something was nil where it should not be. how I can fix the error. Check all the place you use Implicitly Unwrapped Optional type (!) and forced unwrapping (!). In your code shown, there are no forced unwrappings, so you may have some properties with Implicitly Unwrapped Optional type.
Try doing it this way:
if let imageData = pictures[string] {
if let image = UIImage(data: imageData) {
imageView.image = image
}
}
Assuming that string
is a valid key.
You are dealing with optionals, so conditionally unwrap each return object before using it.
Forced unwrapping is dangerous and should only be used when you are absolutely sure that an optional contains a value. Your imageData may not be in the correct format to create an image, but you are forcibly unwrapping it anyway. This is okay to do in Objective-C as it just means nil
objects get passed around. Swift is not so tolerant.
It is the issue of swift when you forget to wrap optional values
Replace line imageView.image = UIImage(data: image!)
with imageView?.image = UIImage(data: image!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With