XCode: Save Time with Custom Code Snippets


As developers, we’re trained to abstract repetitive tasks into reusable components. From variables to functions, keeping things DRY saves time and reduces errors.

In this same vein, XCode’s powerful autocomplete feature saves keystrokes and makes managing verbose method names tolerable. What’s especially nifty about XCode’s autocomplete feature is that developers can harness its power to create their own reusable code snippets.

To demonstrate, let’s create a reusable code snippet that will allow us to quickly autocomplete an implementation for the UITableViewDataSource:tableView:numberOfRowsInSection: method. Typically XCode will create this method skeleton for us, but for the purpose of this exercise, let’s assume our class is written entirely by hand.

We begin with an empty class that inherits from UITableViewController:

Our newly created TableViewController instance must implement the UITableViewDataSource:tableView:numberOfRowsInSection: method. To create our custom code snippet, we’ll start by writing the code for the method by hand:

Once our method is implemented, highlight the method definition in its entirety, and drag the highlighted code snippet into Code Snippet Library section of the Utilities pane:

Drag the newly written code snippet to the Code Snippet Library section of the Utilities page.

Upon releasing the drag, a modal is revealed:

Once the drag is complete, verify that the “Edit” button in the modal is selected.

Give your snippet a descriptive title so you can easily distinguish it from others. Next, let’s the code snippet so the return value is not hardcoded. We’ll use an code completion identifier in place of the hardcoded text so we can easily update the placeholder’s value. To do this, replace the “5" from the code snippet like so:

The “<#” and “#>” produce a code completion identifier. The identifier will be displayed when the code snipper is used and can be easily replaced by pressing the tab key, just like arguments in a method call.

When the code completion identifier is added correctly, XCode will highlight the placeholder:

When the autocomplete identifier is entered correctly, XCode highlights the identifier like so.

Lastly, add a completion shortcut. The shortcut represents the text that, when typed, triggers XCode to present us with our newly created snippet.

The completion shortcut is the text that, when typed, triggers XCode to autocomplete the code snippet.

After selecting an appropriate completion shortcut, click “Done.” Return to the class definition and begin typing the completion shortcut added in the previous step. You’ll see your newly created code snippet presented as an autocomplete suggestion.

Happy Coding! (Or lack thereof ☺)