Better way to manage swift extensions in your project

Photo by Natalia Y on Unsplash

How do we manage extensions in our projects. below screenshot from my project says it all.

For example I have a simple extension UIColor+toImage for generating image from a colour.

usage.

let redImage = UIColor.red.toImage()

perfect isn’t it?

Problem(s)

Readability
1. No one could easily guess whether this function is from original UIColor class or from my custom made extension(unless one go and read into the definition.)
2. The extension are subject to reuse in different projects, so most likely we want them to carry forward into next project. It would be hard to guess the namespace from which it belong.

Solution(s)

One simple and old school way is to use prefix with _ (underscore) before all function names in our extensions.
 eg. my_ or abc_

let redImage = UIColor.red.my_toImage()

But this solution is not manageable as we have to make sure all functions have my_ as prefix.

Swift protocol has got solution for us.

What if we use my.toImage() instead of my_toImage().

So the idea is to make one single module class/struct called MyHelper which will contain all extension methods. Also we can group the functions into extensions if we want.

MyHelperCompatible protocol has got `my` variable which holds entire MyHelper class/struct object.

Now we could extend the MyHelper according to our use. 
eg.

In above file we may add our other helper functions related to UIColor. Similarly we can group alls functions into MyHelper extensions.

Finally we can access toImage() like below.

let redImage = UIColor.red.my.toImage()

From now onwards we just have to create an extension like above and methods into it.

In any case we want to stop this behaviour we can just comment out/remove the conformance part.

// extension UIColor: MyHelperCompatible {}

Tip: Its good to maintain all conformance in a single place rather than scattering around the project so that you have more control.

Final Conclusion:

I understand this seems little tricky and require extra effort to setup one time but believe me it helps to a lot when your project grows.