Every project accumulates code that you write the same way, over and over: a SwiftUI view with its preview, a test suite with its setup, a view model with the same three properties. Typing that structure by hand is slow, and copying it from another file tends to drag along names and details that don't belong in the new context.
Xcode code snippets solve this. A code snippet is a saved block of source code that you can insert from code completion or from the Library. When you add placeholder tokens to a snippet, Xcode inserts the code with those tokens highlighted, so you can jump from one to the next and fill in only the parts that change.
This tutorial shows you how to:
<#Name#> syntax.The steps apply to recent versions of Xcode. Menu names may vary slightly between releases.
A placeholder token is a span of text wrapped in <# and #>. The text between the delimiters is the label that Xcode displays inside the token.
let <#name#> = <#value#>When Xcode inserts code that contains tokens, it renders each one as a rounded, selectable field rather than as raw text. The first token is selected automatically.
Use these keys to work with tokens after insertion:
| Action | Key |
|---|---|
| Move to the next token | Tab |
| Move to the previous token | Shift-Tab |
| Replace the selected token | Start typing |
You've already used tokens without writing them: when Xcode completes a function call, each parameter appears as a token. Your own snippets work exactly the same way.
Note: Each token is independent. If a snippet contains
<#TypeName#>in two places, typing into one doesn't update the other. Design snippets so that each value you need to enter appears once, or accept that you'll fill in repeated tokens individually.
Tip: Write token labels that describe the role of the value, not an example of it.
<#ViewName#>and<#expected result#>tell you what to type;<#Foo#>doesn't.
The fastest way to build a snippet is to write it as real code first, so you can confirm that it's well formed.
Open any Swift file. A scratch file works well, because you'll delete the code afterward.
Type the code you want to reuse, replacing every value that changes with a placeholder token.
Select the code, Control-click the selection, and choose Create Code Snippet. You can also choose Editor > Create Code Snippet.
In the snippet editor that appears, fill in the fields described in the next section.
Click Done, or click outside the editor to save.
Xcode adds the snippet to the Code Snippets section of the Library, alongside the snippets that ship with Xcode.
Important: Tokens typed directly in the source editor become rendered fields immediately, which can make the code hard to select or edit. If that happens, write the code without tokens, create the snippet, and then add the tokens in the snippet editor's code field.
The snippet editor contains several fields. The ones that affect how quickly you can use a snippet are Completion and Availability.
| Field | Purpose |
|---|---|
| Title | The name Xcode shows in the Library and in the completion list. |
| Summary | A short description shown alongside the title. |
| Language | The source language in which the snippet is offered, such as Swift. |
| Platform | Limits the snippet to a specific platform, or makes it available to all. |
| Completion | The text you type in the editor to trigger the snippet. |
| Availability | The code contexts, or scopes, in which the snippet appears in completion. |
The completion shortcut is the most important field. Keep it short, but distinctive enough that it doesn't compete with the names of real types and functions.
A reliable convention is a short, consistent prefix that no Swift API uses, such as your initials or a team abbreviation:
xxview → SwiftUI view with preview
xxsuite → Swift Testing suite
xxtestcase → XCTest case
xxvm → Observable view modelImportant: Xcode doesn't warn you when two snippets share a shortcut, or when a shortcut overlaps one of Xcode's built-in snippets. A unique prefix avoids the problem entirely.
Availability controls the scopes in which Xcode offers the snippet during completion. A snippet that declares a new type only makes sense at the top level of a file; a snippet containing a guard statement only makes sense inside a function.
Choosing the narrowest correct scope keeps your completion list focused and lets you reuse a shortcut for different snippets in different contexts.
New SwiftUI views usually start with the same structure: a type declaration, a body, and a preview. Save that structure once.
import SwiftUI
struct <#ViewName#>: View {
var body: some View {
<#content#>
}
}
#Preview {
<#ViewName#>()
}Configure the snippet like this:
| Field | Value |
|---|---|
| Title | SwiftUI View with Preview |
| Summary | A view type, its body, and a preview. |
| Language | Swift |
| Completion | xxview |
| Availability | Top Level |
To use it, create an empty Swift file, type xxview, and select the snippet from the completion list. Type the view's name, press Tab, and start writing the body. Press Tab again to reach the preview and enter the same name.
Tip: If your views usually take a model or display a specific layout, add that to the template. A snippet that reflects your architecture saves far more time than a generic one.
Tests benefit from snippets in two ways: they remove repetitive setup, and they nudge you toward a consistent structure that makes tests easier to read.
For projects that use the Swift Testing framework, save a suite with a single test written in an arrange, act, assert format:
import Testing
@testable import <#ModuleName#>
@Suite("<#Feature#>")
struct <#Feature#>Tests {
@Test("<#Describe the expected behavior#>")
func <#testName#>() async throws {
// Arrange
<#setup#>
// Act
<#action#>
// Assert
#expect(<#condition#>)
}
}Save a second, smaller snippet for adding individual tests to an existing suite. Set its availability to Class Implementation so it only appears inside a type:
@Test("<#Describe the expected behavior#>")
func <#testName#>() async throws {
// Arrange
<#setup#>
// Act
<#action#>
// Assert
#expect(<#condition#>)
}If your project uses XCTest, the same idea applies with a test case class:
import XCTest
@testable import <#ModuleName#>
final class <#Subject#>Tests: XCTestCase {
private var sut: <#Subject#>!
override func setUp() {
super.setUp()
sut = <#Subject#>(<#dependencies#>)
}
override func tearDown() {
sut = nil
super.tearDown()
}
func test_<#method#>_<#condition#>_<#expectedResult#>() {
// Arrange
<#setup#>
// Act
<#action#>
// Assert
XCTAssert<#Equal#>(<#actual#>, <#expected#>)
}
}Breaking a test method name into three tokens (method, condition, and expected result) makes a naming convention effortless to follow. You fill in each part rather than remembering the pattern.
You can insert a snippet in two ways.
From code completion. Type the completion shortcut in the source editor. When the snippet appears in the completion list, highlight it and press Return.
Note: If predictive code completion is enabled, Tab may accept an inline prediction rather than the highlighted completion item. Press Return to choose the snippet from the completion list.
From the Library. Choose View > Show Library, or press Command-Shift-L, and select the Code Snippets section. Search for the snippet by title, then drag it into the editor or double-click it to insert it at the insertion point.
The Library is useful while you're still learning your shortcuts, or for snippets you use too rarely to remember.
Your snippets change as your codebase changes. To update one:
To remove a snippet, select it in the Library and click Delete.
You can edit and delete only the snippets you create. Xcode's built-in snippets are read-only.
Xcode stores each user-created snippet as an individual file with the .codesnippet extension in your user data directory:
~/Library/Developer/Xcode/UserData/CodeSnippets/Each file is a property list that records the snippet's code, title, shortcut, and scopes. The following trimmed example shows the general shape:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDECodeSnippetCompletionPrefix</key>
<string>xxview</string>
<key>IDECodeSnippetCompletionScopes</key>
<array>
<string>TopLevel</string>
</array>
<key>IDECodeSnippetContents</key>
<string>struct <#ViewName#>: View { ... }</string>
<key>IDECodeSnippetTitle</key>
<string>SwiftUI View with Preview</string>
<!-- Additional keys omitted -->
</dict>
</plist>Important: Create and modify snippets in Xcode rather than authoring these files by hand. The format isn't formally documented, and Xcode relies on keys, such as a unique identifier, that are easy to get wrong.
Because snippets are plain files, you can manage them like any other source:
.codesnippet files in a shared repository. Each developer copies the files into their own CodeSnippets folder.Note: Quit Xcode before copying snippet files into the folder, and reopen it afterward. Xcode reads the folder when it launches.
Snippets are ideal for structures you insert into a file. When you find yourself creating the same kind of file repeatedly, consider a custom file template instead. To learn how to build one, see Xcode Templates Explained - Speed Up iOS Development by Eliminating Boilerplate.
| Use a code snippet when… | Use a file template when… |
|---|---|
| The code goes inside an existing file. | The code defines an entire new file. |
| You need it at a specific insertion point. | You want it available in File > New > File. |
| Manual tokens are enough. | You want values such as the file name or date filled in automatically. |
Snippets insert their contents literally, apart from placeholder tokens. They don't substitute values like the current file name or date.
Keep your snippet library fast and trustworthy with a few habits:
Code snippets turn the structures you type every day into templates you can insert in seconds. Write the code once, replace the parts that change with <#Name#> tokens, and save it with a short completion shortcut and a narrow scope. From then on, a few keystrokes and the Tab key replace minutes of repetitive typing.
Start small. Pick the one block of boilerplate you wrote most often this week, such as a SwiftUI view, a test suite, or a view model, and turn it into a snippet today. As your library grows, keep the snippet files in version control so they evolve with your codebase and your team's conventions.
Thank you for reading. If you have any questions feel free to follow me on X and send me a DM. If this article helped you, Buy me a coffee.