2

I'm using SDWebImage to display images from a firestore database and currently getting the error:

Fatal error: Unexpectedly found nil while unwrapping an Optional value.

Not quite certain how to do the if check to prevent the force unwrapping so would appreciate if anyone can show me an alternate syntax example.

@ObservedObject var movies = getMoviesData()

...

ForEach(self.movies.datas) { item in
        VStack {
             Button(action: {}) {
                 AnimatedImage(url: URL(string: item.img)!)
                  .resizable()
                  .frame(height: 425)
                  .padding(.bottom,15)
                  .cornerRadius(5)                           
              }
         }
}

Also tried comparing to nil (as suggested in the article: What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?) but not working.

enter image description here

pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • Does this answer your question? [What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – pawello2222 Jan 04 '21 at 21:54
  • @pawello2222 Not quite. It says that "the simplest way to check whether an optional contains a value, is to compare it to nil." I'm trying to do that but it's giving conflicting errors. I understand I need a check to make sure the variable has a value, but would appreciate if you or anyone else can give a syntax example pertaining to my code. – Abenezer Bayeh Jan 04 '21 at 22:12

1 Answers1

4

The issue is that you're comparing an unwrapped value with nil. Your program crashes even before the comparison.

You need to compare an optional value instead:

if (URL(string: item.img) != nil) { ... }

Better even to use if-let to make sure that url is not nil:

Button(action: {}) {
    if let url = URL(string: item.img) {
        AnimatedImage(url: url)
            .resizable()
            .frame(height: 425)
            .padding(.bottom, 15)
            .cornerRadius(5)
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209