Better way to manage swift extensions in your project

Image for post
Image for post
Photo by Natalia Y on Unsplash
Image for post
Image for post
let redImage = UIColor.red.toImage()

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()

Swift protocol has got solution for us.

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

let redImage = UIColor.red.my.toImage()
// extension UIColor: MyHelperCompatible {}

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.

Written by

Artist by birth, programmer by choice. 👨🏻‍💻

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store