Visual studio code как запустить код swift
After reading Mattt’s excellent NSHipster article on building the fledgling Swift Language Server Protocol project, I scrolled back up and stared at Step 0: Install Xcode. It didn’t seem strictly necessary, based on what followed. And as I’m sure you’ve deduced by the title and existence of this post, it’s not. Below is a short step-by-step guide to building and running the Swift Language Server Protocol on linux¹. The following instructions assume either a basic understanding of a unix-style command line and/or a willingness to copy and paste superuser commands from the internet into your terminal program of choice.
4. Extract the toolchain and move it to /usr/local/bin :
5. Add Swift to your command line path:
6. Run swift --version to make sure Swift was downloaded and installed correctly. You should see this output (or similar, depending on the version of the toolchain you installed):
7. Clone and build Apple’s sourcekit-lsp project:
8. Move sourcekit-lsp to /usr/local/bin so VS Code can access it.
9. Install Node.js 11.x or newer:
10. Generate the extension for VS Code:
11. Install the extension you just created:
12. Point sourcekit-lsp at your installed toolchain in VS Code’s settings (File > Preferences > Settings > settings.json):
13. Reload your VS Code window (Control+Shift+P > Reload Window) or restart VS Code.
At this point, you’re all set up to use the Swift Language Server on linux.
One big caveat: on Ubuntu 18.04, opening a project with an existing .build folder causes the LSP to crash on launch. A few other caveats:
• SwiftPM build settings are not updated automatically after files are added/removed.
Workaround: close and reopen the project after adding/removing files
• SourceKit-LSP does not update its global index in the background, but instead relies on indexing-while-building to provide data. This only affects global queries like find-references and jump-to-definition.
Workaround: build the project to update the index
Let’s clone and build a sample project:
Now that we’ve cloned the project, open the Splash folder in VS Code to avoid the bug mentioned above.
Finally, we can see it in action:
- Hover over a struct name
- Command+Click to jump to a definition
- Type some code and invoke autocomplete
There has been a lot of enthusiasm around the announcement of this project, and for good reason. It serves as yet another reinforcement of Apple’s broad goals for the Swift programming language, which seem to extend further beyond the friendly confines of their own platforms with each passing year.
Используйте код Visual Studio для разработки на Swift
Visual Studio Code(VSCode)Это кроссплатформенный редактор текста и исходного кода от Microsoft. На сегодняшний день это один из самых интересных проектов с открытым исходным кодом, который регулярно обновляется сотнями участников. VSCode - самая ранняя поддержкаПротокол языкового сервера (LSP)Один из инструментов, последний играет важную роль в обеспечении хорошего опыта разработки для различных языков и технологий.
Некоторое время назад команда Swift объявила о поддержке SourceKit LSP.Сейчас на ранней стадии разработкиТеперь пришло время посмотреть, как эта интеграция работает для нас.
Поэтому мы подробно расскажем о том, как начать использовать поддержку нового языкового протокола сервера Swift в Visual Studio Code на macOS. Если вы не пробовали писать Swift вне Xcode или уже являетесь пользователем VSCode, но плохо знакомы со Swift, то эта статья расскажет вам все, что вам нужно знать.
Поддержка Swift протокола языкового сервера все еще находится на ранней стадии разработки, и в настоящее время нет предварительно созданного пакета языкового сервера (sourcekit-lsp) или расширения Visual Studio Code. Теперь загрузка, сборка и установка этих компонентов и их зависимостей - это ручной процесс, требующий знакомства с командной строкой (при разумной скорости сетевого подключения это занимает около 15 минут).
Когда будет официально выпущена поддержка LSP, все конфигурации будут намного проще.
Шаг 0: установите Xcode
Если Xcode уже установлен на вашем компьютере, откройте приложение терминала и выполните следующую команду:
При выполнении этой команды появится системная подсказка.
Шаг 1. Установите код Visual Studio
ElectronПриложение имеет репутацию большого и медленного, но не отказывайтесь от VSCode из-за этого - его производительность и объем памяти сопоставимы с собственными приложениями.
Шаг 2. Установите последнюю версию набора инструментов Swift.
Шаг 3. Установите узел и NPM
Расширения VSCode написаны на JavaScript / TypeScript. Если вы не готовы к разработке JS, вы можете использоватьHomebrewИспользуйте следующие команды для загрузки Node (среда выполнения JavaScript вне браузера) и npm (диспетчер пакетов Node) илиСледуйте инструкциям для загрузки вручную:
Чтобы проверить, прошла ли установка успешно, выполните следующую команду:
Шаг 4. Соберите и установите SourceKit-LSP
После подготовки всех зависимостей мы готовы приступить к наиболее интересным шагам. Клонировать из командной строкибиблиотека sourcekit-lsp, Перейдите в созданный каталог и создайте проект Swift.
В случае успеха вы можете найти полный двоичный файл из скрытого каталога .build / debug. Переместите двоичный файл в стандартный каталог в $ PATH, например / usr / local / bin или / usr / bin.
Выполните команду sourcekit-lsp, чтобы проверить, все ли работает должным образом:
Эта команда запускает новый процесс языкового сервера, но если она не дает обратной связи для STDOUT, не беспокойтесь, это означает, что она может работать нормально. Для выхода из этого процесса нажмите ^ C.
Шаг 5. Соберите и установите расширение SourceKit-LSP для VS Code
Теперь, когда ваш языковой сервер Swift готов к использованию, последний шаг - это создание и установка расширения Visual Studio Code, чтобы вы могли с ним общаться.
Перейдите в каталог Editors / vscode из каталога sourcekit-lsp на предыдущем шаге, используйте npm для создания расширения и установите его с помощью команды code:
Теперь запустите (или перезапустите) VSCode и откройте проект Swift, напримерНиже, Оцените предварительную версию функций, предоставляемых протоколом языкового сервера Swift.
Чтобы получить полный опыт разработки Swift в VSCode, мы также рекомендуем вам ознакомиться сРасширение языка Swift(Осуществите подсветку синтаксиса до того, как LSP поддержит эту функцию) иРасширение Swift Lint(Диагностика использования в реальном времени).
Теперь у вас есть первоклассный опыт разработки Swift за пределами Xcode. В настоящее время поддержка протокола языкового сервера Swift ограничивается завершением кода, быстрой справкой, диагностикой, переходом к определению символа и поиском ссылок. Тем не менее, мы все еще очень воодушевлены будущим этого проекта, потому что это означаетПерспективы приложений Swift за пределами экосистемы Apple。
An extension for VS Code which provides support for the Swift language, providing the following:
- Completion Lists
- Signature Help
- Snippets
- Quick Info
- Goto Definition
Please note that this extension will ONLY work with Swift Package Manager projects for the time being. If a Package.swift file is not in the root of your project, this extension will fail.
Installation
Obviously, you'll need to have Visual Studio Code installed. Then search for the Swift for Visual Studio Code extension from the command palette ( cmd+shift+p | ctrl+shift+p ).
You'll need to ensure that the swift tool is on your command path is one of the supported versions. As of now, only Swift 3.1 is supported. If you are using development snapshots, you can configure your project to use the correct version of Swift with the `swift-langsrv.
Note: It is entirely possible to use development snapshots. However, they are untested and unsupported. The problem is that the SourceKit binary may simply not load for mis-matched versions of Swift.
swift.toolchainPath - the path to the root of the Swift toolchain, for example: /Library/Developer/Toolchains/swift-3.1.1-RELEASE.xctoolchain
macOS
If you have the correct version of Swift installed, there is no other action necessary as all of the dependencies are installed for you.
Linux (in progress)
The fundamental problem is Swift 3.1 does not build with SourceKit. this is being addressed in Swift 4. There are workarounds that I will published within the next few releases.
Windows Linux Subsystem (experimental)
This setup is identical as the Linux setup with the exception of some additional Visual Studio Code setup that is required. For one, the default shell needs to point to C:\Windows\sysnative\bash.exe . This should be enough to get you going, but your mileage may vary here. In later versions, this will be more flushed out as there are still reliability issues with swift itself in this environment.
Swift JIRA Bug Links
The extension also provides easy hot-links to any of the Swift bugs with a specially crafted comment // SwiftBug(SR-2688) . You can disable this feature with the kiad.swift.enableSwiftBugLinks setting.
Visual Studio Code (VSCode) is a cross-platform text and source code editor from Microsoft. It’s one of the most exciting open source projects today, with regular updates from hundreds of contributors. VSCode was among the first tools to support Language Server Protocol (LSP), which has played a large part in providing a great developer experience, in a variety of languages and technologies.
With the previously announced now shipping in Xcode, it’s a great time to see how this integration works for yourself.
This week, we’ll walk through the process of how to get started with Swift’s new Language Server Protocol support in Visual Studio Code on macOS. If you haven’t tried writing Swift outside Xcode, or are already a VSCode user and new to the language entirely, this article will tell you everything you need to know.
Step 0: Install Xcode
If you don’t already have Xcode installed on your machine, open the Terminal app and run the following command:
Running this command presents a system prompt.
Click the “Get Xcode” button and continue installation on the App Store.
You can verify that everything is working as expected by running the sourcekit-lsp command:
This command launches a new language server process, but don’t worry if it doesn’t provide any feedback to STDOUT — that means it’s working as intended. Exit the process with an ETX signal ( ^ C ).
Step 1: Install Visual Studio Code
Download Visual Studio Code and install it to your system Applications folder. Open the app and follow the instructions for launching from the command line. You’ll need to have the code command accessible from $PATH in order to install the SourceKit-LSP extension later on.
Electron apps have a reputation for being big and slow, but don’t let that stop you from giving VSCode a try — its performance and memory footprint are comparable to a native app.
Step 2: Install Node and NPM
VSCode extensions are written in JavaScript / TypeScript. If you’re not already set up for JS development, you can download Node (a JavaScript run-time for outside the browser)
and npm (a package manager for Node) with Homebrew using the following commands or manually by following these instructions:
To verify that you have a working installation, run the following command:
Step 3: Build and Install SourceKit-LSP Extension for Visual Studio Code
From the command line, clone the sourcekit-lsp repository and navigate to Editors/vscode in the resulting directory. Use npm to build the extension and then use the code command to install it:
Now launch (or relaunch) VSCode and open a Swift project, such as this one, and test out Language Server Protocol support for Swift.
If you get an error stating Couldn't start client Source Kit Language Server , you may also need to specify the sourcekit-lsp executable path, which you can find using xcrun :
Copy the printed value and enter it into the setting for Server Path under Preferences > Settings, Extensions > SourceKit-LSP, and then Reload Window.
To get the full experience of working with Swift from VSCode, we recommend that you also check out the Swift Lint extension (for real-time style and convention diagnostics).
So there you have it — the makings of a first-class Swift development experience outside of Xcode.
And with GitHub’s recent announcement of Codespaces, that future may be coming sooner than we once thought. Thanks to Swift’s support for Language Server Protocol, we’ll soon be able to edit Swift code — syntax highlighting, autocompletion, and all — directly from the browser.
Questions? Corrections? Issues and pull requests are always welcome.
This article uses Swift version 5.2. Find status information for all articles on the status page.
Written by
Mattt (@mattt) is a writer and developer in Portland, Oregon.
With a mouse, anyone can use a computer, even if they aren’t a “computer person”. …though, if you are a “computer person”, you use keyboard shortcuts for most operations, and automate the rest from the Terminal.
Using an IDE other than Xcode for iOS development until recently was a rather lonely path. This however tends to change with recent developments in the Apple ecosystem. Swift runs officially on Linux, Windows, AWS lambda, docker, and other places where you wouldn’t expect to find a programming language made by Apple.
Apple also wants to enable Swift to be a first-class citizen in 3rd party IDEs providing error reporting and code auto-completion. For that reason, they are developing SourceKit-LSP with plugins ready for popular IDEs such as Visual Studio Code (aka VSCode).
Why would you want to use an IDE other than Xcode? Well, Xcode is not available on Linux or Windows in the first place. But even when being on a Mac, VSCode offers several nice features among of them a killer one called Live Share that allows 2 or more developers to collaborate remotely on the same file with live code co-editing. You can think of it as Google Docs for code.
In the days of post-Covid and home office this feature is a real life saver and makes a developer’s life so much easier either if you want to do pair programming or briefly explain and get assistance on a certain task.
If you try to use Swift in VSCode you will get something like that:
The steps needed to enable VSCode for iOS development are basically 3:
- Enable Swift language support
- Add iOS framework support
- Add “app” target support
Since this guide focuses on iOS and this is currently possible only with a Mac for the rest of the guide we will assume we are running on a Mac. Otherwise you can go as far a step 1.
Make sure you have Xcode and VSCode installed. This is the easiest way to hit the ground running since sourcekit-lsp comes prebundled with Xcode. Open a terminal and run:
Assuming that you don’t see any output this is normal and means it works as expected. Hit Ctrl+C to end the process.
Build the SourceKit-LSP extension
Now it is time to build the SourceKit-LSP extension. There is an unofficial SourceKit-LSP — Unofficial CI build but this did not work for me. Building it from source is not that hard. Just make sure you have node.js installed and then run:
After that restart VSCode.
Contrary to what you might read elsewhere you don’t need to edit the source code of the extension at all.
If you try to open a Swift file now you will get an error
Configure the extension
You need to let the plugin know the location of the sourcekit-lsp executable. Open settings.json from VSCode using Cmd+Shift+P and enter “Preferences: Open Settings (JSON)”.
Insert this JSON as the last entry in the existing JSON. Remember to add a comma in the previous line.
What is we achieved so far is to enable Swift development but VSCode has no idea about iOS frameworks. If you try to import UIKit you will get an error.
Insert this JSON in settings.json. You might need to update the x86_64-apple-ios13.6-simulator line based on the current version that you have installed.
This will work for Swift packages that reference iOS frameworks like UIKit.
So far we added iOS support but only for Swift packages. What if you want to work on a typical app target. Trying to open the root folder gives this error:
What if you want to work on an iOS app and not on a Swift Package? SourceKit-LSP always looks for a package.json in root folder assuming that it always deals with a Swift package. An iOS app is not a Swift package and for that reason we need to trick SourceKit-LSP by adding a dummy Package.swift. Add this file to the root of your project (same level as .xcodeproj)
Читайте также: