Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Manage Swift Code Snippets With Xcode

DZone's Guide to

Manage Swift Code Snippets With Xcode

With code snippets, you can save time by saving and reusing a piece of code you use frequently with drag and drop or shortcuts.

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

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 and 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

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 your code:
  • With shortcuts—we'll see in the section "Options" how to assign a shortcut.

Edit Custom Snippets

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 the first suggestion of the autocompletion, we will have the following result:

nameparametersreturn 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 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:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    <#code#>
}

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

This 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:

<# 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:

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:

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:

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:

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 the following image the red areas are top levels:

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

//
//  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:

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

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

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

If you want to hide the hidden files:

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

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

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

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:
ios ,xcode ,code snippets ,mobile ,mobile app development

Published at DZone with permission of Marco Santarossa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}