Reputation: 479
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.
Upvotes: -3
Views: 99
Reputation: 535944
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.
Upvotes: 2