Swift and VSCode

Even though Xcode is a great IDE, it's nice to have options for Swift development - especially on Linux. With the addition of sourcekit-lsp and CodeLLDB, VSCode becomes a good alternative.

sourcekit-lsp

This allows VSCode to connect to sourcekit, which is the engine behind a lot of Xcode features like auto completion and jump to definition.

There is already a great article about getting sourcekit-lsp setup.

Once it's installed you'll be able to use ctrl + spacebar for auto completion suggestions, and get documentation hints when hovering over symbols.

CodeLLDB

Being able to edit Swift code in VSCode is nice, but being able to run and debug it is even nicer.

Install the CodeLLDB extension by searching for it in VSCode's extensions tab.

Create a new VSCode project, and add a Swift file - something simple like the following:

// hello.swift
print("hello")

In the root of your project, make sure there's a .vscode folder, and add the following files:

// launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "lldb",
            "request": "launch",
            "name": "Debug",
            "program": "${fileDirname}/${fileBasenameNoExtension}.bin",
            "args": [],
            "cwd": "${workspaceFolder}",
            "preLaunchTask": "Compile Swift",
            "internalConsoleOptions": "openOnSessionStart"
        }
    ]
}
// tasks.json
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Compile Swift",
            "command": "/usr/bin/swiftc",
            "args": [
                "-g",
                "-o",
                "${fileBasenameNoExtension}.bin",
                "${file}"
            ],
            "type": "shell",
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "options": {
                "cwd": "${fileDirname}"
            }
        }
    ]
}

Now go to the Debug tab in VScode - you'll be able to run your code.

First of all the Swift file will be compiled, outputting a corresponding .dSYM file, and then it's passed to LLDB for execution. The compiled file is configured to have a .bin extension, to make it easier to exclude from source control. What's great about it is you can add breakpoints (unlike Xcode playgrounds). It becomes a really useful little sandbox for experimenting with Swift code.