When doing the front end for our iOS applications we often have to initialize colors. You’ve probably written a lot of code that looks like this in your classes:
Writing this over and over again can become incredibly tedious. When developing a large scale iOS application you may be initializing colors in this manner dozens of times.
Enter Convenience Initializers
Like with many technical problems in Swift we do have a simpler solution, the convenience initializer.
What it does essentially is allow you to call an existing initializer with your own set of parameters. Heres one example to make our UIColor’s a tad bit easier to initialize:
And now we can initialize our colors from before like this:
Ahh, much better, no more dividing by 255 every time! Also, by shrinking the commonly understood words red, green, and blue to r, g, and b we have a much more simple initialization. But we can enhance this a bit more.
Tightening up our solution
This works but we can do more. What if we don’t want to keep writing alpha 1.0 over and over when most of our colors are 100% alpha? Lets make that an optional parameter:
Now we can initialize with either an alpha value of our choice or if its supposed to be 100% we don’t need to fill in alpha at all.
This is better but I think its important we try to write our code with as little repetition as possible. Casting 3 integers to CGFloat and dividing each by 255 seems silly when we can write a little inline function to do that task:
Our new inline function takes our int value, casts it to CGFloat, divides it by 255 and returns the CGFloat value we need for each of the corresponding red, green, and blue values.
Now if Apple decides to change the way UIColor’s are initialized in later versions of Swift instead of updating that functionality in 3 places we have one method where we can take care of things.
Lets take a look at how we can initialize our 3 colors now:
Much, much shorter than the initializer we started with! You can use these same principles to simplify other initializers throughout UIKit or even your own classes.
You can find the full source code for this tutorial on my github here: