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:

Upon releasing the drag, a modal is revealed:

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:

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

Lastly, add a completion shortcut. The shortcut represents the text that, when typed, triggers XCode to present us with our newly created 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 ☺)