Пройдите тест, узнайте какой профессии подходите
Работать самостоятельно и не зависеть от других
Работать в команде и рассчитывать на помощь коллег
Организовывать и контролировать процесс работы
Введение
Swift — это мощный и интуитивно понятный язык программирования, разработанный Apple для создания приложений на iOS, macOS, watchOS и tvOS. Однако, если вы являетесь пользователем Windows и хотите писать на Swift, перед вами могут возникнуть определенные сложности. В этой статье мы подробно рассмотрим, можно ли писать на Swift на Windows, какие инструменты и среды разработки доступны, а также альтернативные способы разработки на этом языке. Мы также обсудим преимущества и недостатки каждого метода, чтобы помочь вам сделать осознанный выбор.

Официальная поддержка Swift на Windows
На момент написания статьи, официальная поддержка Swift на Windows ограничена. Apple изначально разработала Swift для своих операционных систем, и основное внимание уделяется macOS. Однако, сообщество разработчиков активно работает над тем, чтобы сделать Swift доступным и на других платформах, включая Windows. Это означает, что хотя официальной поддержки нет, существуют проекты и инициативы, направленные на перенос Swift на Windows.
Swift for Windows от Apple
Apple официально не предоставляет полноценную поддержку Swift на Windows. Тем не менее, существуют проекты и инициативы, направленные на перенос Swift на Windows. Например, проект Swift for Windows, который предоставляет инструменты и инструкции для установки и использования Swift на Windows. Этот проект активно развивается и поддерживается сообществом, что делает его хорошим выбором для тех, кто хочет попробовать свои силы в разработке на Swift на Windows.
Установка Swift на Windows
Хотя официальной поддержки нет, вы можете установить Swift на Windows с помощью различных методов. Один из самых популярных способов — использование Windows Subsystem for Linux (WSL). WSL позволяет запускать Linux-дистрибутивы на Windows без необходимости использования виртуальной машины, что делает процесс установки более простым и удобным.
Установка через WSL
WSL позволяет запускать Linux-дистрибутивы на Windows без необходимости использования виртуальной машины. Вот шаги для установки Swift через WSL:
-
Установите WSL и выберите дистрибутив Linux (например, Ubuntu). Для этого откройте PowerShell от имени администратора и выполните команду:
После этого перезагрузите компьютер и выберите дистрибутив Linux из Microsoft Store.
-
Откройте терминал WSL и обновите пакеты:
Это необходимо для того, чтобы все пакеты были актуальными и совместимыми с Swift.
-
Установите необходимые зависимости:
Эти пакеты необходимы для компиляции и работы Swift.
-
Скачайте и установите Swift:
Эти команды скачивают и устанавливают Swift на вашу систему.
-
Проверьте установку:
Если все прошло успешно, вы увидите версию установленного Swift.
Инструменты и среды разработки
После установки Swift на Windows, вам понадобятся инструменты и среды разработки для написания и отладки кода. Существует несколько популярных редакторов и IDE, которые поддерживают Swift и могут быть использованы на Windows.
VS Code
Visual Studio Code (VS Code) — это популярный редактор кода, который поддерживает множество языков программирования, включая Swift. Для работы с Swift в VS Code вам понадобятся следующие расширения:
- Swift Language: добавляет поддержку синтаксиса и автодополнения для Swift.
- CodeLLDB: для отладки Swift-кода.
Эти расширения значительно упрощают процесс разработки и делают его более удобным. VS Code также поддерживает множество других полезных функций, таких как интеграция с Git, терминал и различные плагины, что делает его отличным выбором для разработчиков на Swift.
CLion
CLion от JetBrains — это мощная IDE, которая поддерживает множество языков программирования, включая Swift. CLion предоставляет интеграцию с CMake, что позволяет легко настраивать проекты на Swift. Кроме того, CLion предлагает множество инструментов для отладки и анализа кода, что делает его отличным выбором для профессиональных разработчиков.
Альтернативные способы разработки на Swift для Windows
Если установка Swift на Windows кажется вам сложной или неудобной, существуют альтернативные способы разработки на этом языке. Эти методы могут быть более простыми и удобными, особенно если вы только начинаете изучение Swift.
Использование виртуальной машины
Вы можете установить macOS на виртуальную машину с помощью программного обеспечения, такого как VirtualBox или VMware. Это позволит вам использовать Xcode — официальную среду разработки от Apple, которая поддерживает Swift. Вот основные шаги для установки macOS на виртуальную машину:
- Скачайте и установите VirtualBox или VMware.
- Найдите образ macOS и создайте новую виртуальную машину.
- Установите macOS на виртуальную машину и настройте Xcode.
Этот метод позволяет вам использовать все возможности Xcode и macOS, но требует больше ресурсов и времени на настройку.
Облачные среды разработки
Существуют облачные среды разработки, такие как Repl.it и Gitpod, которые позволяют писать и запускать код на Swift прямо в браузере. Это удобный способ начать изучение Swift без необходимости установки дополнительных инструментов. Облачные среды разработки также предлагают множество полезных функций, таких как совместная работа и интеграция с GitHub.
Кросс-платформенные фреймворки
Фреймворки, такие как Flutter, позволяют писать кросс-платформенные приложения на Swift и Dart. Это может быть полезно, если вы хотите разрабатывать приложения для нескольких платформ одновременно. Flutter предоставляет множество инструментов и библиотек, которые упрощают процесс разработки и делают его более эффективным.
Заключение
Хотя официальная поддержка Swift на Windows ограничена, существуют различные способы установки и использования этого языка на платформе Windows. Вы можете воспользоваться WSL, виртуальными машинами или облачными средами разработки. Каждый из этих методов имеет свои преимущества и недостатки, и выбор подходящего метода зависит от ваших потребностей и предпочтений. Надеемся, что эта статья помогла вам разобраться в возможностях разработки на Swift для Windows и выбрать наиболее подходящий для вас метод.
Читайте также
Tools
Your favorite editor likely already supports Swift. Below are setup guides for some popular choices.
-
Xcode
Xcode is a complete IDE enabling you to develop, test, debug, and distribute apps for all Apple platforms on macOS.
Learn more
-
Visual Studio Code
Visual Studio Code is a cross-platform and extensible editor that supports Swift through the Swift extension, which provides intelligent editor functionality as well as debugging and test support.
Learn more
-
Emacs
Emacs is an extensible cross-platform text editor. Swift editing support can be enabled through community-provided packages.
Learn more
-
Neovim
Neovim is an extensible cross-platform text editor. Swift editing support can be enabled through your pick of community-provided plugins.
Learn more
-
Other Editors
Any editor that supports the Language Server Protocol (LSP) can use SourceKit-LSP to provide intelligent editor functionality for Swift.
Learn more
Привет, Хабр!
Сегодня я поделюсь своим опытом страданий установки языка программирования Swift под Windows в форме небольшого рассказа и постараюсь описать те проблемы, с которыми я столкнулся при попытке развернуть детище Apple на платформе конкурента.
Начну издалека. Я являюсь мобильным разработчиком под Андроид и периодически люблю развлекать себя различными экспериментами. Совсем недавно ко мне в руки попал Mac Mini на Apple Silicon — в офисе был бесхозный компьютер от яблочной корпорации и в один момент я захотел собрать свой пет-проект на KMP (бывш. КММ) под айос, посмотреть, как оно будет работать. (И будет ли работать вообще) Плюсом меня давно тянуло к макоси, было интересно за что ее кто-то обожает, а кто-то терпеть не может. Забавно, что нейтрального мнения я не встречал ни разу.
Установка Swift
В первую очередь, я решил зайти на официальный сайт Swift и посмотреть, поддерживает ли он ОС от Майкрософт. К моему счастью, добрые дяди (или тети) программисты уже попотели за меня и добавили поддержку ЯПа в винду, начиная с 10ки.
Переходим в инструкции для нужной нам ОС и видим это:
Нас просят изначально поставить некоторый список зависимостей. Ставим сначала Visual Studio (в моем случае 2022). При установке выбираем «Разработка классических приложений на С++». Как только поставилось, листаем чуть ниже.
И вот тут лично у меня было некоторое смятение. К чему относиться блок ниже? К scoop? winget? Почему он так оформлен, будто является частью большого заголовка? Может, я придираюсь, но, честно говоря, это совсем неочевидно.
Хорошо. Будем действовать одним из самых древних методов познания – методом тыка.
Пробуем сначала поставить winget и запустить указанные скрипты, предварительно немного их изменив:
winget install Git.Git
winget install Python.Python.3 --version 3.10.2150.0
winget install Python.Python.3.9
winget install Microsoft.VisualStudio.2022.Community --force --custom "--add Microsoft.VisualStudio.Component.Windows10SDK.19041 --add Microsoft.VisualStudio.Component.VC.Tools.x86.x64"
В чем разница? Сразу же можно заметить, что мы устанавливаем кроме Python 3.10 еще и Python 3.9. Это потребуется нам, когда мы будем собирать наш проект. Так же я просто поменял версию студии, так как скрипт написан для 2019, а у меня 2022.
Будем считать, что первый шаг сделан. Листаем инструкцию дальше.
Видим, что теперь нас просят установить сам свифт, я предпочитаю скачать exe-шник, поэтому поставлю его.
На этом казалось бы все. Свифт стоит у вас на компьютере и можно даже что нибудь написать и запустить. Ведь можно же, да? Нет. На самом деле компилятор и все тулзы у вас действительно установлены, но вот нет никакой инфраструктуры, чтобы можно было хоть что то написать и запустить. Сейчас кто-то может возразить, мол, есть же Swift REPL, интерактивный редактор кода, который идет в комплекте со свифтом, в нем же тоже можно писать код. Безусловно можно, но лично у меня возникла такая проблема:
Это вынудило меня искать обходной путь.
Установка инструментов разработки
Буквально сразу в мою голову закралась мысль: «А что, если мы будем использовать VS Code?». Иногда мне кажется, что в этом простеньком редакторе можно или вскоре будет можно даже программировать ядерные реакторы, достаточно будет лишь доставить необходимые плагины для работы. Конкретно сейчас мы ядерные реакторы не программируем, но гибкость VS Code нам так же очень пригодится.
Ставим сначала редактор, после того как поставили ставим плагин для свифта. В нем есть: подсветка кода, дебаггинг, автодополнение, запуск .swift файлов (об этой функции мы поговорим чуть позже) и много чего еще, полный список можно найти в карточке плагина.
После того как поставили, пробуем наконец таки запустить наш простенький код на свифте:
print(“Hello world!!!”)
Жмем Ctrl + Shift + P и выбираем «Swift: Run swift script». И тут лично меня ждало еще одно разочарование:
Пораскинув мозгами, я пришел к единственно верному решению – отобрать у VS Code его работу и собирать и компилировать скрипты самостоятельно, вводя команды в cmd. Не самый приятный исход, но вполне себе терпимый.
Создаем папку под на будущий проект, после чего, находясь внутри созданной нами директории, прописываем в cmd следущее:
swift package init
Далее переходим в папку Sources/<PROJECT NAME>
и создаем там файл с именем main и расширением .swift (Обязательно файл должен иметь имя main, так как пакету нужна входная точка для исполнения кода). Итого файл должен называться так: main.swift
.
После всего этого открываем наш main.swift
в VS Code и пробуем запустить все тот же код.
Кажется, что это все и теперь мы можем спокойно выполнить наш код, но не тут-то было:
Оказывается, у нас беды с конфигурацией пакета, поэтому, в первую очередь, необходимо устранить эту проблему. Поднимаемся наверх по директориям, пока не дойдем до корневой папки пакета, где лежит файл Package.swift
. Открываем его.
Меняем
let package = Package(
name: <PROJECT NAME>,
products: [
// Products define the executables and libraries a package produces, making them visible to other packages.
.library(
name: <PROJECT NAME>,
targets: [<PROJECT NAME>,])
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.target(
name: <PROJECT NAME>,),
.testTarget(
name: <PROJECT NAME TESTS>,
dependencies: ["<PROJECT NAME>,"])
]
)
На
let package = Package(
name: <PROJECT NAME>,
products: [
// Products define the executables and libraries a package produces, making them visible to other packages.
.executable(
name: "main",
targets: ["<PROJECT NAME>"])
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.target(
name: <PROJECT NAME>,
dependencies: []),
.testTarget(
name: <PROJECT NAME TESTS>,
dependencies: [<PROJECT NAME>])
]
)
Сохраняем изменения. Находясь в директории, где лежит файл main.swift
запускаем команду:
swift run
Вуаля, код заработал, можно открывать шампанское.
Стоит отметить, что, возможно вы столкнетесь с такой проблемой, когда компилятор просто соберет готовый исполняемый файл, но не запустит его. Чтобы это решить перейдите сначала в корневую директорию проекта (папка .build/x86_64-unknown-windows-msvc\debug
), там найдите файл main.exe и запустите его. Если он будет сразу же закрываться после запуска, то добавьте в конце всего кода функцию readLine()
и тогда консоль не будет закрываться сразу же, а будет ждать ввод любой клавиши.
Когда я устанавливал все это дело в первый раз, я столкнулся с проблемой, которую не мог решить, после нескольких дней своих изысканий было решено забить на установку свифта прямо на винду и сделать все через WSL. Я проследовал всем инструкциям, что были указаны на сайте для установки свифт под Линукс, но опять забрел в тупик и решил бросить это дело в принципе. Но в тот же день я заметил, что ни один из установленных компиляторв C++ не может собрать простейший проект. Каждый как под копирку твердил, что не может найти необходимые файлы при линковке, естественно я начал свое расследование, что же послужило причиной выхода из строя линковщика. Искал я очень упорно, но результатов все не было, я удалил свифт с винды, переустановил начисто Visual Studio 3 раза, но ничего не помогало. И, наконец, на третий день я вспомнил про wsl и снес все пакеты, что я поставил во время той злосчастной установки. Каково же было мое счастье, что после всех попыток разобраться, я в кой то веке нашел ответ. Как уже стало ясно из рассказа, установка свифта из под wsl ломает линковщик компиляторов С++ (в частности, MSVC и GCC). Поэтому, никогда ни за что, ни при каких обстоятельствах, не совершайте этой ошибки. Она может стоить слишком дорого.
После этого, на удивление, я снова захотел поставить свифт, только теперь более основательно подойти к процессу. Результатом этого желания стала данная статья.
Заключение
Напоследок, хочу сказать, что это был крайне незабываемый опыт. Можно отметить, что документация в некоторых местах оставляет желать лучшего и хотелось бы более понятной инструкции к установке, так же, конечно, сказывается отсутствие нормального инструментария.
Надеюсь, эта ситуация изменится в лучшую сторону.
Swift is a powerful and popular programming language, especially for Mac and iOS app development. While it’s true that Swift is native to Apple’s ecosystem, you don’t necessarily need a Mac to learn and code in Swift. In this guide, we will explore how to program in Swift on a Windows 10 machine. We’ll cover the basics, including setting up an editor, writing a simple Swift program, and compiling it on Windows.
Understanding Swift
Before diving into Swift on Windows, let’s take a moment to understand what Swift is and why it’s worth learning.
What Is Swift?
Swift is a modern programming language developed by Apple. It draws inspiration from various programming languages like Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and more. Chris Lattner, the project originator, designed Swift to be efficient, easy to read, and versatile.
Despite being relatively young, Swift has gained widespread popularity since its public release in 2014. In fact, it rapidly climbed the ranks on the TIOBE Index, becoming one of the fastest-growing programming languages.
In essence, Swift is the language of choice for developers looking to create applications for Mac and iOS platforms.
Getting Started with Swift on Windows 10
To begin coding in Swift on Windows, you’ll need an editor to write your code. While you can use any Integrated Development Environment (IDE) you prefer, we’ll start with a straightforward option: Notepad++. It’s free, user-friendly, and suitable for our introductory purposes.
Setting Up Notepad++
- Download Notepad++: Visit the official Notepad++ website and download the application for Windows.
- Installation: Install Notepad++ by following the on-screen instructions.
With Notepad++ ready, let’s create a simple Swift program.
A Simple Swift for Windows Program
In this section, we will create a basic Swift program that runs in the Windows command line.
- Open Notepad++: Launch Notepad++.
- Writing the Program: Begin by writing the following code:
swift
// This will display when the program runs.
print("Hello! How's your day?")
This code prints a question to the screen.
- User Input: To gather user input, add the following lines:
swift
let response = readLine()
This code reads the user’s response and stores it in the
response
variable. - Displaying the Response: Now, display a message based on the user’s input:
swift
print("Have a great day, \(response!)!")
Here, we use string interpolation to include the user’s response in the message.
Note: The
!
afterresponse
denotes that it’s not an optional value, indicating that it must have a value. - Save Your Code: Go to “File” > “Save As” and select “Swift file” from the “Save As Type” menu. If “Swift file” isn’t available, choose “All files” and add the
.swift
extension to your chosen filename.
Compiling Swift in Windows 10
Now that you have a Swift program, you’ll need a way to compile and run it on Windows 10. While there is no native Swift support on Windows, there is a workaround.
Using the Swift for Windows Compiler
- Download the Compiler: Han Sangjin has developed a Swift compiler for Windows, available on GitHub. Download the Swift for Windows application following the provided instructions in the link.
- Installation: Install the Swift for Windows application on your system.
- Compile Your Program: Open the Swift for Windows application, click “Select File,” and choose the Swift program you created earlier. Click “Compile” and wait for the process to complete. For small programs, this should be nearly instant.
- Run Your Program: Once the compilation is successful, click “Run,” and your Swift program will execute in the Windows Command Line.
Conclusion
While Swift is primarily associated with macOS and iOS development, Windows users can still explore and learn the language with the right tools and setup. Notepad++ serves as a suitable text editor for writing Swift code on Windows, and the Swift for Windows compiler allows you to compile and run your programs seamlessly.
As you delve deeper into Swift, you’ll discover a wealth of resources and opportunities to enhance your coding skills. Whether you’re an aspiring developer or looking to expand your programming repertoire, Swift on Windows is a viable path to explore the world of app development.
So, why wait? Begin your Swift coding journey on Windows today, and who knows, you might soon be crafting innovative Mac and iOS applications of your own.
-
Tags
How to Program in Swift on Windows 10
Learn how to get started with the Swift Programming Language in Windows.
To be honest, although may not want to work totally with this language on this environment to create applications or something like that, you may find very useful the fact of programming in this language in a Windows environment just for learning purposes of the language itself and its syntax. It’s worth to mention that not everyone can afford the purchase of an apple device to work with this language, so if you are one of those that work in a windows environment and you may like to introduce yourself to the Swift Language, then you have found the correct article to get started with.
The Swift Language is a high-performance system programming language with a very clean and modern syntax, that offers seamless access to existing C and Objective-C code and frameworks, being memory safe by default. Although inspired by Objective-C and many other languages, Swift is not itself a C-derived language. As a complete and independent language, Swift packages core features like flow control, data structures, and functions, with high-level constructs like objects, protocols, closures, and generics. Swift embraces modules, eliminating the need for headers and the code duplication they entail. The open source SwiftForWindows project provides an easy-to-use development environment for Swift programming for Windows applications. The project works with the Swift compiler for Cygwin, MSVC, MinGW.
In this article, we’ll show you an easy way to get started with the programming with the Swift Language in a Windows Environment.
1. Download SwiftForWindows compiler
As first step, you need to download the installer of Swift For Windows from the releases page of the project at Github here. The installer file size is around 110MB and you will be the one who decides where to install it. By default, it’s installation path is at C:/Swift. Now you need to understand how the project works, after installing Swift For Windows, you will basically have at your disposition an executable that works as a compiler, it offers a graphical user interface that allows you to select the swift source file that you want to compile:
You need to compile the file before running it, so if your code is valid and you click on Compile, you will be able to run it with the Run button, which normally will open a command prompt with the output of your code if there’s any of course. For more information about this project, please visit the official repository at Github here.
2. Testing the compiler
To get started with the compiler, let’s write some code ! Create a file somewhere on your system namely hello.swift
. This file will have the following code inside:
print("Hello World !")
To define the file that the compiler should compile, click on Select File. This will open the system filebrowser and will allow you to select a file, select the file we’ve just created. The steps to run your Swift code on this environment is the following:
- Click on Compile
- If the compilation succeeds, click on Run
With the code that we wrote on our hello.swift
file, the output will be:
Note that while the command prompt with the output of your Swift Code is opened, the compiler tool will be blocked, so be sure to close the cmd window before trying to compile again. However, not everything in the life is printing hello world on every new programming language that you learn! You may want to get started with more complex code, for example the fibonacci series. Create a new file namely fibonacci.swift
and paste the following code:
class FibIterator : IteratorProtocol {
var (a, b) = (0, 1)
func next() -> Int? {
(a, b) = (b, a + b)
return a
}
}
let fibs = AnySequence{FibIterator()}
print(Array(fibs.prefix(10)))
Compile it and run it. As expected, the output will be:
About the logs
During the compilation, the compiler will have a log that is displayed directly in the application. This log contains the warnings, notes or errors of the code that is being compiled. You will not always get a Successfully compiled message in the output, so you will need to pay attention to the other kind of messages in the log. Note that once you Run the compiled code (which means your application compiled succesfully, as long as there’s not an older version of your program), the log will be removed, so check it immediately after trying to compile. As on every sane compiler, you will get the line and character where the exception/warning occurs.
Errors
The compiler will be able to deal with errors during the compilation, for example with the following code that should display the date in the output:
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let year = components.year
let month = components.month
let day = components.day
print(year)
print(month)
print(day)
Will throw the following errors (error: use of unresolved identifier 'Calendar' and 'Date'
):
This error in our code is cause by the missing import statement at the beginning of our code ‘import Foundation
‘, the functional snippet is shown in the warnings area.
Warnings
The compiler will display warnings as well, if we fix our previous snippet importing the Foundation namespace, our code will compile succesfully:
import Foundation
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let year = components.year
let month = components.month
let day = components.day
print(year)
print(month)
print(day)
However, we’ll get some warnings and notes:
- warning: expression implicitly coerced from ‘Int?’ to Any. This warnings is triggered cause of the print function, that requires a set of Any parameters. String is a Any. In this case the compiler is telling you that it implicitly coerced the optional string into an Any object (by transforming the String value in Optional(value)).
- note: force-unwrap the value to avoid this warning. When an object is optional and you want to access one of its methods or properties, you will need to ‘unwrap’ it.
The output of our running code will be:
In conclusion, you can see how easily it is to get started with the Swift programming language or at least with its syntax in Windows. Notice that as there’s no official API that exposes how to do specific things in Windows, like opening a File browser, a program or related, this project is made entirely for strict learning purposes of the language in a different environment.
Happy coding !