Lukas Pistrol Logo

Lukas Pistrol

Xcode: Code Snippets

Sometimes it can be helpful to save boilerplate code as a snippet which you can simply copy and paste into your currently opened file.

While there are a lot of great apps to do so, Xcode offers its own snippet manager. You might have already seen it before when writing basic control flow statements e.g. if statements:

If Statement Completion

This will then expand to this including some nifty placeholders:

If Statement Expanded

Create your own Snippet

Let's say we want a snippet to quickly add todos to our project. Anywhere in you project write the following:

// TODO: <#TODO#>

The part in between the <# & #> tags defines a placeholder exactly like in the example above.

Now select the line, right click and select Create Code Snippet....

Create Code Snipper

A new window will appear and you can edit your code snippet further by giving it a name or summary description. You can even define which language and in which scope your snippet should be available. However the most important field is the Completion one. This will define on which input text Xcode will show the the snippet in the code completion. In this case todo should be good.

Edit Code Snippet

You can also open this window any time by pressing Shift + Command + L in Xcode. As you can see in the screenshot above you can browse and search already present snippets.

Now close the window and somewhere in your code start typing todo or whatever you entered in the Completion text field and you should see your new snippet appear immediately.

Code Snippet Completion

After pressing return, thanks to the placeholder value you can simply start typing the content of your todo.

Custom Code Snippet With Placeholder

Another article you might like: