Sunday, 30 July 2017

Swift In Practice: Using Asset Catalog Identifiers


The usual way of handling things


Usually , we will be accessing image from asset catalogs as given below. For example, we have an asset catalog which contains three images.



Common Implementation


Whats wrong with the above usage


We will be using this hard coded image name informations in lot more places in our code. And any typo mistake will create bugs and the developer may unaware of this, since compiler will not capture typo errors in hard coded strings.

So how can we approach these problems in a more robust way and make our code more clean.

As a solution, we can use some global string constants. But is that adequate? the answer is No. See the following code.



It is clear, that UIImage designated initialiser can take any string constants , which will not show any errors during complication but will throw exception at run time. So , this can introduce some problems.

So its better to use strongly typed strings for asset catalog identifiers by making use of application specific enums. Also if we add a convenience initialiser to UIImage with a parameter named as "assetIdentifier" or something else according to your taste it will be perfect, Please refer the implementation given below.

Asset Catalog enums and UIImage convenience initialiser implementation




Asset Catalog Identifier Usage


Advantages

1. Typo errors in image names can be avoided since we are using enums. Which will result in compilation errors incase of Typo errors.

2. UIImage initialisers always returned with an image object.

3. Its easy identify unused images in your code by commenting an enum type. Which will not produce any compilation issue if the respective image is unused.

4. The class or file can be used a centralised source of your resources where you can find all of your image names.

References:

1. WWDC Video - Swift In Practice