Swift in Visual Studio Code
Swift is a general-purpose programming language that's approachable for newcomers and powerful for experts.It is fast, modern, safe, and a joy to write. This topic goes into detail about setting up and using Swift within Visual Studio Code, with theswiftlang.swift-vscode extension.
The Swift extension includes:
- Syntax highlighting and code completion
- Code navigation features such as Go to Definition and Find All References
- Refactoring and quick fixes to code
- Package management and tasks with support for Swift Package Manager
- Rich support for debugging
- Testing with XCTest or Swift Testing frameworks
The Swift extension is designed to support the following projects:
- Swift Package Manager projects (e.g. using a
Package.swift
) - Projects that can generate a
compile_commands.json
(e.g. using CMake)
Install the extension
- First, install Swift. If you do not already have Swift installed on your system, see theGetting Started Guide on Swift.org.
- Download and installVisual Studio Code.
- Install the Swift extension from theVS Code Marketplaceor directly from within the VS Code extensions pane.
Create a new Swift project
To create a new Swift project, you can use theSwift: Create New Project...
command inthe Swift extension to guide you through the process. You can find this command by openingthe Command Palette and following the instructions below.
- For macOS:CMD+Shift+P
- Other platforms:Ctrl+Shift+P
- Choose the type of project you'd like to create from the list of templates.
- Choose the directory where the project will be stored.
- Give your project a name.
- Open the newly created project. You will be prompted to open the project inthe current window, a new window, or add it to the current workspace. Thedefault behavior can be configured by using the
swift.openAfterCreateNewProject
setting.
Language features
The Swift extension usesSourceKit LSPto power language features. SourceKit LSP provides the following features in theeditor. Use these links to see the VS Code documentation for each topic:
SourceKit LSP also provides code actions to automate common tasks. Code actions in VS Codeappear as a light bulb near the editor margin (see the below screenshot for anexample of this). Clicking on the light bulb will show you the available actionswhich can include:
- Adding targets to your
Package.swift
- Converting JSON to protocols
- Adding documentation to your functions
Prior to Swift 6.1 you must perform aswift build
command on your project eitheron the command line or using a task in VS Code before language features can be used.This populates the index in SourceKit-LSP.
Swift tasks
Visual Studio Code provides tasks as a way to run external tools. See theIntegrate with External Tools via Tasksdocumentation to learn more.
The Swift extension provides some built-in tasks that you can use to build viaSwift Package Manager. You can also configure custom tasks by creating atasks.json
file in the root folder of your project. For example, thistasks.json
builds of your Swift targets in release mode:
{ "version":"2.0.0", "tasks": [ { "type":"swift", "label":"Swift Build All - Release", "detail":"swift build --build-tests", "args": ["build","--build-tests","-c","release"], "env": {}, "cwd":"${workspaceFolder}", "group":"build" } ]}
The above task is configured to be in thebuild
group. This means it willappear in therun build tasks
menu that can be opened withCMD+Shift+Bon macOS orCtrl+Shift+B on other platforms:
Any errors that occur during a build appear in the editor as diagnosticsalongside those provided by SourceKit-LSP. Running another build task clears thediagnostics from the previous build task.
Debugging
Visual Studio Code provides a rich debugging experience. See theDebugging documentation formore information.
The Swift extension relies on theLLDB DAP extension to enabledebugging support.
By default, the extension creates a launch configuration for each executabletarget in your Swift package. You may configure these yourself by adding alaunch.json
file to the root folder of your project. For example, thislaunch.json
launches a Swift executable with custom arguments:
{ "configurations": [ { "type":"swift", "name":"Debug swift-executable", "request":"launch", "args": ["--hello","world"], "cwd":"${workspaceFolder}", "program":"${workspaceFolder}/.build/debug/swift-executable", "preLaunchTask":"swift: Build Debug swift-executable" } ]}
You can launch a debugging session via the Debug view in VS Code.
- Select the launch configuration you wish to debug.
- Click on the green play button to launch a debugging session.
The executable will be launched and you can set breakpoints inyour Swift code that will be hit as code executes.
The screenshot below shows an example of debugging a Hello World program. Itis paused on a breakpoint and you can see that the Debug View shows the valuesof variables in scope. You can also hover over identifiers in the editor to seetheir variable values:
Test Explorer
Visual Studio Code provides a Test Explorer view in the left sidebar which canbe used:
- To navigate to tests
- To run tests
- To Debug tests
The Swift extension supportsXCTest as well asSwift Testing.As you write tests they are automatically added to the Test Explorer.
To debug a test:
- Set a breakpoint
- Run the test, suite, or entire test target with the
Debug Test
profile.
TheRun Test with Coverage
profile instruments the code under test and opens acode coverage report when the test run completes. As you browse covered files,line numbers that were executed during a test appear green, and those that weremissed appear red. Hovering over a line number shows how many times coveredlines were executed. Line execution counts can be shown or hidden using theTest: Show Inline Coverage
command.
Swift Testing tests annotated withtagscan be filtered in the Test Explorer using@TestTarget:tagName
. You can thenrun or debug the filtered list of tests.
The Swift VS Code extension does not support running Swift Testing tests in Swift 5.10 or earlier.
Advanced toolchain selection
The Swift extension automatically detects your installed Swift toolchain.However, it also provides a command calledSwift: Select Toolchain...
whichcan be used to select between toolchains if you have multiple installed.
This is an advanced feature used to configure VS Code with a toolchain otherthan the default on your machine. It is recommended to usexcode-select
onmacOS orswiftly
on Linux to switch between toolchains globally.
You may be prompted to select where to configure this new path. Your options areto:
- Save it in User Settings
- Save it in Workspace Settings
Keep in mind that Workspace Settings take precedence over User Settings:
The Swift extension will then prompt you to reload the extension in order topick up the new toolchain. You must do so, otherwise the extension will notfunction correctly: