дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
162 рядки
16 KiB
Plaintext
162 рядки
16 KiB
Plaintext
---
|
||
title: "Swift"
|
||
description: "Swift code intelligence with sourcekit-lsp for SwiftPM and Xcode projects, formatting, SwiftLint, single-file runs and debugging with lldb-dap."
|
||
---
|
||
|
||
OpenIDEA supports Swift through [sourcekit-lsp](https://github.com/swiftlang/sourcekit-lsp), the language server that ships with the Swift toolchain. Highlighting, folding and the outline work without any setup. Completion, navigation, diagnostics, refactorings and formatting come from sourcekit-lsp. For the other languages, see the [support matrix](/en/languages/index).
|
||
|
||
| Language | Extensions | Language server | Debugger |
|
||
| -------- | --------------------------- | --------------- | -------- |
|
||
| Swift | `.swift`, `.swiftinterface` | sourcekit-lsp | lldb-dap |
|
||
|
||
## Setup
|
||
|
||
The IDE does not install Swift tools. Install a toolchain, which brings `swift`, `sourcekit-lsp` and `lldb-dap`:
|
||
|
||
- **macOS**: install Xcode, or only the Command Line Tools (`xcode-select --install`). Xcode is needed for iOS, macOS app and other Apple platform projects.
|
||
- **Linux and Windows**: install a toolchain from [swift.org](https://www.swift.org/install).
|
||
|
||
When `sourcekit-lsp` is not found, opening a Swift file shows an install hint instead of an **Install** button. On macOS, `/usr/bin/sourcekit-lsp` runs the copy from the Xcode chosen with `xcode-select` (or `DEVELOPER_DIR`, see [Several Xcode versions](#several-xcode-versions)). To use another binary, set **Executable** for sourcekit-lsp in **Settings › Languages & Frameworks › Language Servers**.
|
||
|
||
## New projects
|
||
|
||
**File › New Project** creates Swift projects in two ways:
|
||
|
||
- **Swift** runs `swift package init` and makes a SwiftPM package: an executable, a library or a command-line tool.
|
||
- **Xcode Project** writes an Xcode project without any generator tool (no XcodeGen or Tuist). It works like Xcode's template chooser: pick a platform tab (**Multiplatform**, **iOS** or **macOS**), then a template from the **Application** or **Framework & Library** section (**Filter** narrows them; double-click a template, or select it and click **Continue**). The next page asks for the project's options:
|
||
|
||
| Option | What it sets |
|
||
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
||
| **Product Name** | The project, target and scheme name. Letters, digits, spaces, hyphens and underscores. |
|
||
| **Team** | `DEVELOPMENT_TEAM`, a 10-character Team ID. Empty signs to run locally, which is enough for the simulator and the Mac. |
|
||
| **Organization Identifier** | The bundle identifier's prefix, such as `com.example`. The IDE offers the one you used last. |
|
||
| **Bundle Identifier** | Read-only: the organization identifier and the product name, with characters a bundle identifier cannot have replaced by `-`. |
|
||
| **Interface**, **Language** | SwiftUI and Swift. |
|
||
| **Testing System** | **Swift Testing** or **XCTest** for a unit-test target (apps also get an XCTest UI-test target), or **None**. |
|
||
|
||
The templates are **App** (a SwiftUI app: `<Name>App.swift`, `ContentView.swift` and `Assets.xcassets` with AppIcon and AccentColor; a Multiplatform app is one target for iOS and macOS) and **Framework** (a Swift framework). The project needs Xcode 16 or newer: its folders are synchronized folders, so files you add later in the IDE belong to their target without editing `project.pbxproj` (see [New files in Xcode projects](#new-files-in-xcode-projects)). It has a shared scheme named after the product, so the new project opens with its scheme and a simulator chosen, ready for **Run** and the tests (see [Xcode schemes](#xcode-schemes)).
|
||
|
||
## Language server
|
||
|
||
sourcekit-lsp finds the workspace root by looking up from the file for one of these files: `Package.swift`, `buildServer.json`, `compile_commands.json` or `.sourcekit-lsp`. The outermost folder within the project that has one becomes the root; without any, the project folder is the root.
|
||
|
||
sourcekit-lsp then reads the build settings for that root:
|
||
|
||
- **SwiftPM**: a root with `Package.swift` works without setup. sourcekit-lsp resolves the package and its dependencies itself.
|
||
- **Build server**: a `.bsp/*.json` file or a `buildServer.json` in the root points sourcekit-lsp at a Build Server Protocol server. Xcode projects use this (see [Xcode projects](#xcode-projects)).
|
||
- **`compile_commands.json`**: a compilation database, for example from CMake.
|
||
|
||
### Package dependencies
|
||
|
||
Right-click `Package.swift` in the Project view or the editor, or use **Find Action** (`⇧⌘A` / `Ctrl+Shift+A`):
|
||
|
||
- **Resolve Swift Packages** runs `swift package resolve`: it fetches the dependencies and writes `Package.resolved`.
|
||
- **Update Swift Packages** runs `swift package update`: it moves the dependencies to the newest versions `Package.swift` allows.
|
||
|
||
Both run in the **Run** tool window in the folder of `Package.swift`. sourcekit-lsp watches `Package.swift` and `Package.resolved` and reloads the package when either changes, including after `git pull`, so completion for a new dependency works without restarting the server.
|
||
|
||
`.sourcekit-lsp/config.json` holds sourcekit-lsp's own options; see the [sourcekit-lsp configuration reference](https://github.com/swiftlang/sourcekit-lsp/blob/main/Documentation/Configuration%20File.md).
|
||
|
||
### Xcode projects
|
||
|
||
sourcekit-lsp cannot read `.xcodeproj` or `.xcworkspace` files. Without a build server, files in an Xcode project get no build settings, and you see errors such as "No such module". Generate a `buildServer.json` in the project root with one of these tools:
|
||
|
||
- **[xcode-build-server](https://github.com/SolaWing/xcode-build-server)**: `brew install xcode-build-server`, then in the project root:
|
||
|
||
```bash
|
||
xcode-build-server config -workspace App.xcworkspace -scheme App
|
||
```
|
||
|
||
Use `-project App.xcodeproj` instead of `-workspace` for a project without a workspace. xcode-build-server takes the compile flags from Xcode's build logs, so build the scheme once in Xcode or with `xcodebuild` first, and build again after adding files or changing build settings. When the project has no build log yet, the IDE builds what Run builds once in the background, at low priority (**Building … for code insight** in the status bar, with Cancel), and restarts sourcekit-lsp when it ends; Run then builds on top of it. It skips this while Xcode is using the build folder. Turn it off with **Settings › Build, Execution, Deployment › Compiler › Build Xcode projects in the background for code insight**.
|
||
|
||
- **[sourcekit-xcode-bsp](https://github.com/slime-studio/sourcekit-xcode-bsp)**: needs Xcode 26 or newer. Install it with `brew install slime-studio/tap/sourcekit-xcode-bsp` and run `sourcekit-xcode-bsp init` in the project root; it finds the `.xcworkspace` or `.xcodeproj` itself and targets the iOS Simulator by default (the `platform` field in `buildServer.json`). It is an early release (0.1.x).
|
||
|
||
Open the folder that contains `buildServer.json` (or `.bsp/`) as the project, or a parent of it with no other root marker between, so that it is the workspace root. After generating the file, reopen the project so that sourcekit-lsp starts with it.
|
||
|
||
<Tip>`buildServer.json` holds absolute paths for your machine. Add it to `.gitignore` instead of committing it.</Tip>
|
||
|
||
**Clean Build Folder** (**Build › Xcode**, Find Action, or right-click the `.xcodeproj` / `.xcworkspace`) runs `xcodebuild clean` for the selected Xcode scheme in the Run tool window, with the same flags a run uses. **Delete DerivedData** moves this project's DerivedData folder (the one `xcodebuild -showBuildSettings` reports, plus the IDE's own run builds) to the Trash after asking, then restarts sourcekit-lsp. Other projects' DerivedData is left alone.
|
||
|
||
### New files in Xcode projects
|
||
|
||
`xcodebuild` compiles only the files a target lists, and the IDE does not edit `project.pbxproj`. What happens to a source file you create, rename or delete depends on how the project lists its files:
|
||
|
||
- **Synchronized folders** (Xcode 16 and newer): files in a folder shown with a blue folder icon in Xcode's navigator belong to the folder's targets as soon as they are on disk. To turn a classic group into one, right-click it in Xcode and choose **Convert to Folder**. New Xcode 16 projects use synchronized folders.
|
||
- **Classic groups**: a new file must be added to a target in Xcode (**File › Add Files to…**, or drag it into the group). When a new `.swift`, `.m`, `.h` or other source file isn't named in `project.pbxproj`, the IDE says so, with **Open in Xcode**.
|
||
- **[XcodeGen](https://github.com/yonaskolb/XcodeGen) (`project.yml`) and [Tuist](https://tuist.dev) (`Project.swift`)**: the project is generated from the spec, so after files change the IDE offers to regenerate it (`xcodegen generate` or `tuist generate --no-open`) in the Run tool window. **Regenerate Xcode Project** in **Find Action** (`⌘⇧A` / `Ctrl+Shift+A`), or in the context menu of `project.yml` and `Project.swift`, runs it any time.
|
||
|
||
### CocoaPods
|
||
|
||
In a project with a `Podfile`, the schemes of the `.xcodeproj` build through the `.xcworkspace` that `pod install` writes next to it, for run and test configurations alike, and the `Pods/` folder gets no run configurations of its own. Right-click the `Podfile`, or use **Build › Xcode** or **Find Action**:
|
||
|
||
- **Pod Install** runs `pod install`; **Pod Update** runs `pod update`.
|
||
|
||
Both run in the **Run** tool window in the folder of the `Podfile`, with the `pod` on your `PATH`; the IDE does not install CocoaPods. When the run succeeds, run configurations are detected again, and a `buildServer.json` that xcode-build-server generated for the project is generated again for the workspace. When `Pods/Manifest.lock` is missing or differs from `Podfile.lock` as the project opens, the IDE offers **Pod Install**.
|
||
|
||
### Several Xcode versions
|
||
|
||
To use a specific Xcode in a project, choose it under **Xcode** in **Settings › Languages & Frameworks › Swift** (the list shows the Xcodes in `/Applications` and `~/Applications`), or in the project's `settings.toml`:
|
||
|
||
```toml
|
||
[languages.swift]
|
||
xcode = "/Applications/Xcode-beta.app"
|
||
```
|
||
|
||
Everything the IDE starts in the project gets it as `DEVELOPER_DIR`: sourcekit-lsp, `xcodebuild` (run, test, Clean Build Folder), `simctl`, lldb-dap, coverage reports and new terminals. It also overrides a `DEVELOPER_DIR` from `.envrc`. Changing it restarts sourcekit-lsp. Empty uses the Xcode chosen with `xcode-select`.
|
||
|
||
## Formatting
|
||
|
||
**Reformat Code** (`⌥⌘L` / `Ctrl+Alt+L`) uses sourcekit-lsp, which formats with [swift-format](https://github.com/swiftlang/swift-format) from the same toolchain. swift-format reads its options from a `.swift-format` file in the file's folder or a parent folder.
|
||
|
||
## SwiftLint
|
||
|
||
In a project with a `.swiftlint.yml`, the IDE checks Swift files with [SwiftLint](https://realm.github.io/SwiftLint/) as you type and shows its findings as warnings and errors in the editor and in the **Problems** tool window, with the rule name (for example `line_length`) as the code.
|
||
|
||
- **Configuration**: SwiftLint runs in the folder of the `.swiftlint.yml` nearest to the file, up to the project folder, and uses that file. Swift files below no `.swiftlint.yml` in the project are not checked.
|
||
- **Saved and unsaved text**: an opened or saved file is checked by its path, so the configuration's `excluded` paths and nested configurations apply. Unsaved edits are sent to SwiftLint through stdin (`--use-stdin`), which checks them against the nearest configuration only; a file that `excluded` lists stays unchecked while you edit it.
|
||
- **Installing**: the IDE runs the `swiftlint` it finds on `PATH` or in its tools folder, and never installs it on its own. Install it with `brew install swiftlint`, or with **Install** next to SwiftLint (under Swift, **Command-Line Tools**) in **Settings › Languages & Frameworks › Language Servers**. When `swiftlint` is missing in a project that has a `.swiftlint.yml`, the IDE says so once.
|
||
- **Restricted Mode**: SwiftLint does not run in projects you have not trusted.
|
||
|
||
To fix what SwiftLint can correct, run `swiftlint --fix` in the terminal. The IDE does not offer SwiftLint quick fixes yet.
|
||
|
||
## Run and debug
|
||
|
||
### Single files
|
||
|
||
A `.swift` file can be run with **Run Context Configuration** (`⌃⇧R` / `Ctrl+Shift+F10`). The IDE runs `swift <file>` with the `swift` on your `PATH`.
|
||
|
||
### SwiftPM packages
|
||
|
||
Each executable product in `Package.swift` gets a **swift run \<product\>** run configuration. Its before launch task runs `swift build --product <product>`, then **Run** starts `swift run --skip-build <product>` in the package folder. Tests under `Tests/` get gutter icons that run `swift test --filter`.
|
||
|
||
### Xcode schemes
|
||
|
||
Each scheme of a `.xcodeproj` or `.xcworkspace` in the project root gets an **Xcode App** run configuration, with the scheme's launch arguments and environment variables. Run builds the scheme with `xcodebuild` and then:
|
||
|
||
- **iOS apps** are installed and launched on the simulator chosen in the toolbar, or on the one the configuration's **Simulator** field pins.
|
||
- **macOS apps** are built with `-destination 'platform=macOS'`, and the app's executable (`<App>.app/Contents/MacOS/<App>`) runs directly: its output shows in the Run console, and **Stop** quits it. No simulator is booted.
|
||
- **Apps that support both** run on the simulator. Set **Simulator** to `macos` to run them on the Mac instead.
|
||
|
||
As in Xcode, the Run console shows the app's output, not the build's. The `xcodebuild` output goes to a build log that the console links after the build (`Build log: …`); a failed build also prints its error lines there. Errors and warnings reach **Problems** either way. The simulator's `Class … is implemented in both` warnings and `simctl`'s `<bundle id>: <pid>` line are left out.
|
||
|
||
### Coverage of Xcode tests
|
||
|
||
**Run › Run with Coverage** on an Xcode test configuration runs `xcodebuild test -enableCodeCoverage YES` and reads the result bundle with `xcrun xccov`. The [Coverage](/en/guide/coverage) tool window and the editor gutter show the app and framework sources of the project; files that only test targets (`.xctest` bundles) compile and files outside the project, such as the SDK and DerivedData, are left out. Covered lines with a region that never ran (an `if` whose `else` was skipped) are marked partial.
|
||
|
||
### Debugging
|
||
|
||
Debugging uses lldb-dap. On macOS the IDE finds Xcode's copy through `xcrun -f lldb-dap`; elsewhere it comes with the Swift toolchain on `PATH`.
|
||
|
||
Start a **swift run \<product\>** configuration with **Debug** (`⌃D` / `Shift+F9`). The before launch task builds the product as for **Run**, the IDE asks `swift build --show-bin-path` where it was written (with the configuration's build options, such as `-c release`), and lldb-dap launches it with the configuration's arguments, environment and working folder. Program output goes to the **Debug** console. Debugging `swift test` runs is not supported yet.
|
||
|
||
To debug another Swift executable, add a **Program** configuration with **Executable** set to its path and **Debug adapter** set to **lldb-dap (C, C++, Swift)**. **Attach to Process…** also attaches to a running Swift program with lldb-dap when CodeLLDB is not installed. See [Debugging](/en/guide/debugging) for breakpoints, stepping and the variables view.
|
||
|
||
## Limitations
|
||
|
||
- `swift test` runs cannot be debugged yet.
|
||
- Xcode projects need a `buildServer.json` that you generate yourself (see [Xcode projects](#xcode-projects)).
|
||
- **Expand Macro** does nothing: sourcekit-lsp shows the expansion in a new document, which the IDE does not open yet.
|
||
- There is no SwiftUI Preview, Interface Builder, asset catalog editor or simulator integration. Use Xcode for those.
|
||
- sourcekit-lsp and lldb-dap are not installed by the IDE.
|
||
- SwiftLint findings have no quick fixes; run `swiftlint --fix` yourself.
|