Contents

Manage Swift Code Snippets With Xcode


Do you write hundreds of lines of code every day? Would you like saving time typing less code? Well, Code Snippet Library may become your favourite Xcode feature.

Overview

The concept of code snippets is saving a piece of code which we write often. In this way, we can reuse these snippets easily thanks to shortcuts or drag & drop.

In this article, I’ll describe how Xcode manages the code snippets and then how to create a custom one using also advanced options provided by the IDE.

Happy Reading! đź‘Ť

Code Snippet Library

What Is It?

The Code Snippet Library is a list of code snippets available in Xcode.

We can find this library in the Utilities Menu:

How To Add A Custom Snippet

By default, Xcode provides several snippets. If those are not enough for our needs, we can add custom ones.

The steps to add a new code snippet is:

  1. Select the code which we want to add.
  2. Grab the selection with left-click
  3. Drag inside the code snippet.

You can watch the demonstration in the following video:

How To Use A Snippet

There are two ways to use a code snippet:

  • Select it with left-click in the Code Snippet Library and drag inside our code:

  • With shortcuts—we’ll see in the section “Options” how to assign a shortcut.

Edit Custom Snippet

Once we add a new snippet, we’ll be able to edit it with a double-click and clicking the button Edit:

Placeholder Tokens

If we type func inside a class and press the button return ↩ in first suggestion of the autocompletion, we will have the following result:

name, parameters, return type and function body are called placeholder tokens. If you click one of them and start typing something, you’ll notice that you can easily replace the placeholder with what you’re typing.

You can easily change the placeholder focus with the Tab button to move to the next one, whereas with Shift+Tab you can move to the previous one.

If we want to add a placeholder token in our code snippet we can add <## token_text #> in the body of our snippet—change token_text with whatever you want:

Options

In the edit mode we can also change several options for each custom snippet.

Title / Summary

These two fields allow us to add a title and a subtitle to our code snippet. By default the snippet has the title My Code Snippet.

The problem of leaving the default title is that if we add more than one snippet, we will have a lot of My Code Snippet. Thus, the library becomes confusing and we’ll have difficulties to find a specific snippet.

If we edit the values like this:

We’ll have the following result in the library:

Completion Shortcut

Before explaining the other options, we must understand how to assign a shortcut, because the other options work just when we add a snippet using a shortcut—the drag & drop ignores the options.

By default, this value is empty, therefore we can’t use a shortcut to add the snippet.

We can add a new shortcut—t1—like this:

In this way, if in our code we type t1 then the autocompletion will suggest our snippet:

Platform

We can decide if the shortcut should work just with a specific platform like iOS, macOS and so on.

We may have two code snippets with the same shortcut, one for iOS and one for macOS.

Language

We can decide in which language the shortcut should work. By default, the language is the one used in the project.

In this article, we use Swift.

Completion Scopes

We can decide if the shortcut should work just in a specific scope. By default, the value is All, therefore it works everywhere.

We may want some specific scopes, and we can also combine them with + button:

Class implementation

We can decide if the shortcut should work just inside a class implementation. It would work also in structs and Swift extensions.

We may use this option for the implementation of a delegate—like UITableViewDataSource:

1
2
3
4
5
6
7
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
	<#code#>
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
	<#code#>
}

Which should be added just inside a class or an extension.

Code Expression

We can decide if the shortcut should work just inside an expression.

We may use this option with a snippet which is a ternary operator:

1
<## condition #> ? <## true #> : <## false #>

Then, we can use this snippet like this:

tern is the shortcut and Ternary Operator is the title of the snippet.

Function or Method

We can decide if the shortcut should work just inside a function/method.

We may use this option with a snippet which is a return with a placeholder token:

1
return <## value #>
String or Comment

We can decide if the shortcut should work just inside strings and comments.

We may use this option with a snippet which is a log message with a default prefix:

1
MarcoSantaDev's Log: <## message #>

Then, we can use it like this:

cl is the shortcut and Custom Log is the title of the snippet.

Another example, to use with the comments, can be a TODO message:

1
TODO: <## message #>

And we can use it like this:

tm is the shortcut and TODO Message is the title of the snippet.

Another useful usage of this option is with the MARK message:

1
MARK: - <## message #>
Top Level

We can decide if the shortcut should work just at the top-level.

Top level means outside any class/function, in following image the red areas are top levels:

We may use this option with a snippet which is a custom copyright header like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//
//  MyObject.swift
//
//  Copyright © 2017 Marco Santarossa (https://marcosantadev.com)
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

Delete A Custom Snippet

If we want to remove a custom code snippet from the library, we can select with left-click the one which we want to remove and then press the button delete ⌫.

🚨 Pay attention, we cannot undo this operation. Once we delete a code snippet, we won’t be able restore it. 🚨

Note that we can delete just custom snippets and not the default ones.

Import/Export Custom Snippets

We can find our custom code snippets at the path ~/Library/Developer/Xcode/UserData/CodeSnippets/.

Since Library is a hidden folder, we can either open this path with the terminal command:

1
open ~/Library/Developer/Xcode/UserData/CodeSnippets/

Or you can let the Finder shows the hidden files with the terminal command:

1
defaults write com.apple.Finder AppleShowAllFiles true && killall Finder

If you want to hide again the hidden files:

1
defaults write com.apple.Finder AppleShowAllFiles false && killall Finder

Every time we add/remove files in this folder, we must restart Xcode.

Conclusion

All of us may have personal code snippets depending on how we write our code. Anyway, we can find a list of popular code snippets in the Github repository XcodeSwiftSnippets.