Faryar Fathi

Composer, Coder, Entrepreneur

Organizing Import Directives in Xcode

When writing code, I often end up with quite a few (sometimes repetitive) #import directives on top of my implementation files. Blame it on trying to write good, modular code!

Xcode doesn’t have an Organize Imports feature by default . But I picked up a nice tip in “Working Effectively with Xcode” WWDC video a while ago on how to create an organize imports service with a little bit of help from Automator.

Here’s how:

  1. Launch Automator and create a new Service:

  1. Search for Run Shell Script action and drag it into the right-hand panel:

  1. Check “Output replaces selected text” and enter sort | uniq in the script window.

  1. Now save the service and give it a name, something like “Sort & Unique” or “Organize”, etc.

Congratulations! You now have a “Sort & Unique” (or whatever you named it) service available to you in Xcode (and other applications actually) under the services menu.

To use it, highlight the code that you want to organize, right click on it and select your new service in the Services menu.

Have fun satisfying all your OCD tendencies!