Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpectedly found nil while unwrapping optional value [duplicate]

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?

like image 758
Ben Gray Avatar asked Oct 31 '14 13:10

Ben Gray


People also ask

How do you fix fatal error unexpectedly found nil while unwrapping an optional value?

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.

What kind of error occurs when you force unwrap an optional that contains nil?

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.

What does thread 1 fatal error unexpectedly found nil while implicitly unwrapping an optional value mean?

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.


2 Answers

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.

like image 135
Anorak Avatar answered Sep 19 '22 16:09

Anorak


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!)

like image 25
iOS Developer Avatar answered Sep 18 '22 16:09

iOS Developer