-3

While running the below code, I got following error: "Unexpectedly found nil while unwrapping an Optional value". Here's the code:

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
        let imageData = Data.init(base64Encoded: imageString, options: .init(rawValue: 0))
        let image = UIImage(data: imageData)
        return image!
    }

So to overcome the issue I used guard let image data but what should I return? I cannot just use return and leave it empty as function expects UIimage output. Really confused which "default" value to pass in this case to wrap nil error.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Mel
  • 429
  • 1
  • 4
  • 12
  • How about changing the return type to `UIImage?` and return `nil` (this way you don't even need `guard let`)? If you _must_ return a `UIImage`, then you should really ask _yourself_ what image you want this function to return when base64 decoding fails. – Sweeper Nov 01 '21 at 13:01
  • 1
    Change your function to return an optional, and don't load it on the other side if its nil. Change your function to throw an error and again catch it on the calling side. Or else provide a default image if your code always must load an image. Force unwrapping should be avoided at all costs – Simon McLoughlin Nov 01 '21 at 13:02

1 Answers1

2

Do not return an incorrect empty image. You need to signal somehow to the caller that the conversion has failed. You have basically two choices, returning an Optional (where nil means failure) or throwing an error:

func convertBase64StringToImage (imageBase64String:String) -> UIImage?

or

func convertBase64StringToImage (imageBase64String:String) throws -> UIImage

Either way, now the caller knows clearly that there was a problem, and it is up to the caller to cope.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • did not work. or maybe I didn't get what you meant. I only added "?" after UIImage just like you said and didn't touch the code. And changed "let image = UIImage(data: imageData!)"...added "!". still getting same error – Mel Nov 01 '21 at 13:23
  • Do not add `!` _anywhere_. It is nearly always wrong. — My answer stands. I've told you the correct thing to do. I'm not planning to write your actual code for you. – matt Nov 01 '21 at 13:40