A Beautiful Solution to Non-Optional UIImage Named in Swift

Yesterday, I got around to watching the Swift in Practice WWDC15 Session, and I LOVED the suggestion for dealing with Image naming in Swift.

The big issue of course is that UIImage:named: takes a hard-coded string, and returns an optional UIImage. That means dealing with potential mis-spellings and unnecessarily unwrapping optionals throughout your application.

Of course one way to deal with this is to have one file of Image Constants, but that doesn’t deal away with the optional image problem. With Swift, there is an even better solution. You can extend UIImage to include an enum of all your image names, and create a convenience initializer that initializes your image via an enum:

So now, whenever you need to use an image anywhere in your application, you just initialize it like this:

Note how clean this is! First, you get to use a nice enum value – no more hard-coded Strings! Oh, and the enum auto-completes for you! And second, the image is no longer an optional – you’re guaranteeing that it’s there.

One of my favorite take-aways from this WWDC session is the notion of letting the compiler help you. By using an enum value for image names, you’re getting the compiler to do the work of auto-completing and checking that your image is there.

I wanted to test this out for myself, so I created a small sample project on Github here. Check it out if you’d like to see how this would be used in an application.

Update

As several people pointed out, there are open source libraries that with a script for exporting your image names into enums.

Check out:

Feel free to add any additional ones in the comments!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.