Topics

#109: Xcode Code Snippets 🐰

Topics

Today we're talking Code Snippets. These are a great way to speed up our workflow. A well-kept library of snippets can save us hours of writing repetitive boilerplate code. Let's take a look.

We'll begin by opening the Utilities sidebar by clicking the button on the far right of the toolbar. Then we'll click the curly braces { } icon in the bottom panel to see our library of snippets.

Xcode ships with a decent starting set of snippets, but the real power comes when we start to define our own. Let's make a snippet for something we do all the time: Hopping to a background queue, then hopping back to the main queue to update some UI.

We'll start by writing some code we want to make a snippet. We can put this anywhere, we'll delete it when we're done:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
  // background code

  dispatch_async(dispatch_get_main_queue()) {
    // main queue code
  }
}

Next, we'll replace those comments with some tokens. When we use our snippet, we'll be able to press the tab key to cycle through each token and easily replace it. Tokens are defined like this:

<# token name #>

We'll replace our two comments with tokens, then select our whole snippet and drag and drop the code itself onto our library of snippets. A panel will open, where we'll be able to describe our snippet, and configure when it can be triggered.

We'll use hop for our completion shortcut, then click Done, to try it out. Beginning to type hop and pressing tab now inserts our code. Success!