Marcel Voss

Quick Tip: Safely using UIImage

by Marcel on June 2, 2023

I don’t know about you, but it happens quite often to me that I want to use a UIImage instance and assign it to another piece of UI that requires it to be non-optional. Unfortunately, most UIImage initializers produce optionals. While this does make sense, as the asset might be missing or there has been a typo in its name, it can be quite annoying when were sure the asset exists and can be used. But don’t worry, there’s an easy trick to work around behavior.

extension UIImage {
    static func safeImage(named: String) -> UIImage {
        guard let image = UIImage(named: named) else {
            assertionFailure("No image with name \(named) could be found.")
            return UIImage()

        return image

This simple extension for UIImage does exactly what I want: try initializing a UIImage instance with the name of the asset that I’d like to use, if there is not asset with that exact name, it will assert and inform us while debugging and return an empty UImage instance. If the asset was found, it will simply return the newly created UIImage instance that contains the asset. Very simple, very but surprisingly useful. Of course, we could have achieved a similar effect with force unwrapping but that would also make our app crash in production, only because an asset couldn’t be found.