Creating an UIImage using ImageIdentifiers
Hi! In my first post I want to share with you some cool tip which I watched in 'Swift in Practice - Apple WWDC 2015' Alex Migicovsky presentation about using UIImages in Swift project.
Normally you create UIImageView with UIImage like this :
or like this
But what happens If you have typos (e.g. "rign") in file name or there is not an image named "ring" ? Nothing. You don't get any warnings or errors from a compiler. Everything will compile without problems. But unfortunately our UIImageView will be empty and definitely you don't want it.
Also let's say you're working on a big project and you use UIImages in many places, then you discover you have a typo in an image name. Of course you don't get any warning or error and you have to go through the whole project and find all usages of this image and possibly fix it.
Now, let's try to deal with this problem...
1.Create special Enum for all UIImages used in project.
2.Create convenience initializer for UIImage
Some of you can say "Ok, ok... but what if I have typos in some ImageIdentifier value ?" That's the point. Best advantage of this solution is that you have only one place where all images are placed and it is only place where you can fix it. You don't have to search whole project and find usages of the image.
Another advantage is that you will get autocomplete on UIImage constructor, and choosing proper image will be easiest.
As you can see I have a typo in name of enum value, but now I will get a compiler error saying :
(...)type 'ImageIdentifier' has no member 'GoldRign'
So compiler can help you with creating UIImage !
In essence, I hope all of you want to write a safe and clean code. You'll get a cleaner code because you have one place in your code where all images are defined and you’ll get a safer code because a compiler or IDE can help you while creating the UIImage.
Previously swift did not support optional initializers for UIImage and above lines of code looked like this
Now swift added the concept of failable initializers and the UIImage initializer returns an optional so if UIImage cannot be created it will be nil. Maybe now this concept lose some value because you don't have to care about unwrapping image but I truly recommend you to use this UIImage concept in your projects.
Hope that help you!
This article is cross-posted with my my personal blog.