-3
Image(uiImage: image ?? UIImage(named: "photo")!)
    .resizable()
    .frame(width: 300, height: 300)

Crash error

Implicity unwrapped nil value

How can I unwrap this?

koen
  • 5,383
  • 7
  • 50
  • 89
  • 3
    Any time you say `!` you are _saying_ "please crash me". You can hardly complain when that's exactly what happens. – matt Feb 14 '23 at 19:52
  • Does this answer your question? [How do you unwrap Swift optionals?](https://stackoverflow.com/questions/25195565/how-do-you-unwrap-swift-optionals) – koen Feb 14 '23 at 22:59

1 Answers1

3

How can I unwrap this?

According to the error message, you've got an implicitly unwrapped nil value. That is, you have some variable declared like:

var image: UIImage! = ...

You should only ever use implicit unwrapping when you know for certain that the object will exist as soon as the variable is initialized, and that it will continue to exist for the life of the variable.

The way to fix your problem is to either ensure that the object exists, which is not currently the case since you're getting nil, or stop using implicit unwrapping. You could, for example, change your variable declaration to something like:

var image: UIImage? = ...

Then you'd have a regular optional that you could attempt to unwrap normally as you're doing in the first line of your question.

Caleb
  • 124,013
  • 19
  • 183
  • 272
  • 1
    I would add that `UIImage(named: )` is usually a great place to use implicitly unwrapped optionals. This returns `nil` when the named image is not found in the asset catalog, which is an issue for the developer to resolve, and not an error that can come about because of any user action. – Hayden McCabe Feb 14 '23 at 23:38