Swift package manager windows

Installation via Windows Package Manager

Windows Package Manager (aka WinGet) comes pre-installed with Windows 11 (21H2 and later). It can also be found in the Microsoft Store or be installed directly.

  1. Enable Developer Mode:

    In order to develop applications, particularly with the Swift Package Manager, you will need to enable developer mode. Please see Microsoft’s documentation for instructions about how to enable developer mode.

  2. Install Windows platform dependencies:

    The required C++ toolchain and Windows SDK are installed as part of Visual Studio 2022. The instructions below are for the Community edition, but you may want to use a different Visual Studio edition based on your usage and team size.

    winget install --id Microsoft.VisualStudio.2022.Community --exact --force --custom "--add Microsoft.VisualStudio.Component.Windows11SDK.22000 --add Microsoft.VisualStudio.Component.VC.Tools.x86.x64 --add Microsoft.VisualStudio.Component.VC.Tools.ARM64"
    
  3. Install Swift and other dependencies:

    Install the latest Swift developer package, as well as compatible Git and Python tools if they don’t exist.

    winget install --id Swift.Toolchain -e
    

Package Manager

The Swift Package Manager (SwiftPM) is a tool for managing the distribution of Swift code.
It’s integrated with the Swift build system
to automate the process of downloading, compiling, and linking dependencies.

The Package Manager is included in Swift 3.0 and above.

This section describes the basic concepts that motivate
the functionality of the Swift Package Manager.

Swift organizes code into modules.
Each module specifies a namespace
and enforces access controls on which parts of that code
can be used outside of the module.

A program may have all of its code in a single module,
or it may import other modules as dependencies.
Aside from the handful of system-provided modules,
such as Darwin on macOS
or Glibc on Linux,
most dependencies require code to be downloaded and built in order to be used.

When you use a separate module for code that solves a particular problem,
that code can be reused in other situations.
For example, a module that provides functionality for making network requests
can be shared between a photo sharing app and a weather app.
Using modules lets you build on top of other developers’ code
rather than reimplementing the same functionality yourself.

A package consists of Swift source files and a manifest file.
The manifest file, called Package.swift,
defines the package’s name and its contents
using the PackageDescription module.

A package has one or more targets.
Each target specifies a product
and may declare one or more dependencies.

A target may build either a library or an executable as its product.
A library contains a module that can be imported by other Swift code.
An executable is a program that can be run by the operating system.

A target’s dependencies are modules that are required by code in the package.
A dependency consists of a relative or absolute URL to the source of the package
and a set of requirements for the version of the package that can be used.
The role of the package manager is to reduce coordination costs
by automating the process of downloading and building all of the dependencies for a project.
This is a recursive process:
A dependency can have its own dependencies,
each of which can also have dependencies,
forming a dependency graph.
The package manager downloads and builds everything that is needed
to satisfy the entire dependency graph.


The following section assumes a working knowledge of Swift.
If you’re new to the language,
you may want consult one of the introductory resources first.
We recommend A Swift Tour in
The Swift Programming Language.

If you want to follow along with the code examples,
you’ll need to have a working installation of Swift.
You can find instructions for how to install Swift in
Getting Started.

In Getting Started,
a simple command-line tool is built with the Swift Package Manager.

To provide a more complete look at what the Swift Package Manager can do,
the following example consists of three interdependent packages:

  • PlayingCard — Defines PlayingCard, Suit, and Rank types.
  • DeckOfPlayingCards — Defines a Deck type that shuffles and deals an array of PlayingCard values.
  • Dealer — Defines an executable that creates a DeckOfPlayingCards, shuffles it, and deals the first 10 cards.

You can build and run the complete example
by downloading the source code of the Dealer project from GitHub
and running the following commands:

$ git clone https://github.com/apple/example-package-dealer.git
$ cd example-package-dealer
$ swift run dealer <count>

We’ll start by creating a target representing
a playing card in a standard 52-card deck.
The PlayingCard target defines the PlayingCard type,
which consists of a Suit enumeration value (Clubs, Diamonds, Hearts, Spades)
and a Rank enumeration value (Ace, Two, Three, …, Jack, Queen, King).

public enum Rank: Int {
    case two = 2
    case three, four, five, six, seven, eight, nine, ten
    case jack, queen, king, ace
}

public enum Suit: String {
    case spades, hearts, diamonds, clubs
}

public struct PlayingCard {
    let rank: Rank
    let suit: Suit
}

By convention, a target includes any source files located in the Sources/<target-name> directory.

example-package-playingcard
├── Sources
│   └── PlayingCard
│       ├── PlayingCard.swift
│       ├── Rank.swift
│       └── Suit.swift
└── Package.swift

Because the PlayingCard target does not produce an executable,
it can be described as a library.
A library is a target that builds a module which can be imported by other packages.
By default, a library module exposes all of the public types and methods
declared in source code located in the Sources/<target-name> directory.

When creating a library package intended for use as a dependency in other projects,
the Package.swift manifest must reside at the top level/root of the
package directory structure.

Run swift build to start the Swift build process.
If everything worked correctly,
it will compile the Swift module for PlayingCard.

The complete code for the PlayingCard package can be found at
https://github.com/apple/example-package-playingcard.

The DeckOfPlayingCards package brings in the previous package:
It defines a Deck type.

To use the PlayingCards module, the DeckOfPlayingCards package must declare
the package as a dependency in its Package.swift manifest file.

// swift-tools-version:5.3
import PackageDescription

let package = Package(
    name: "DeckOfPlayingCards",
    products: [
        .library(name: "DeckOfPlayingCards", targets: ["DeckOfPlayingCards"]),
    ],
    dependencies: [
        .package(url: "https://github.com/apple/example-package-playingcard.git", from: "3.0.0"),
    ],
    targets: [
        .target(
            name: "DeckOfPlayingCards",
            dependencies: ["PlayingCard"]),
        .testTarget(
            name: "DeckOfPlayingCardsTests",
            dependencies: ["DeckOfPlayingCards"]),
    ]
)

Each dependency specifies a source URL and version requirements.
The source URL is a URL accessible to the current user that resolves to a Git repository.
The version requirements,
which follow Semantic Versioning (SemVer) conventions,
are used to determine which Git tag to check out and use to build the dependency.
For the PlayingCard dependency will use the most recent version with a major version equal to 3.

When the swift build command is run,
the Package Manager downloads all of the dependencies,
compiles them,
and links them to the package module.
This allows DeckOfPlayingCards
to access the public members of its dependent modules
with import statements.

You can see the downloaded sources in the .build/checkouts directory at the root of your project,
and intermediate build products in the .build directory at the root of your project.

The complete code for the DeckOfPlayingCards package can be found at
https://github.com/apple/example-package-deckofplayingcards.

With everything else in place,
now you can build the Dealer module.
The Dealer module depends on the DeckOfPlayingCards package,
which in turn depends on the PlayingCard package.
However, because the Swift Package Manager automatically resolves transitive dependencies,
you only need to declare the DeckOfPlayingCards package as a dependency.

// swift-tools-version:5.5

import PackageDescription

let package = Package(
    name: "dealer",
    products: [
        .executable(name: "Dealer", targets: ["Dealer"]),
    ],
    dependencies: [
        .package(url: "https://github.com/apple/example-package-deckofplayingcards.git", from: "3.0.0"),
    ],
    targets: [
        .target(
            name: "Dealer",
            dependencies: ["DeckOfPlayingCards"]),
    ]
)

Swift requires that a source file import the modules for any types
that are referenced in code.
For the Dealer module’s main.swift file,
the Deck type from DeckOfPlayingCards
and the PlayingCard type from PlayingCard are referenced.

import DeckOfPlayingCards

let numberOfCards = 10

var deck = Deck.standard52CardDeck()
deck.shuffle()

for _ in 1...numberOfCards {
    guard let card = deck.deal() else {
        print("No More Cards!")
        break
    }

    print(card)
}

By convention, a target containing a file named main.swift in its directory
produces an executable.

Running the swift build command
starts the Swift build system
to produce the Dealer executable,
which can be run from the .build/debug directory.

$ swift build
$ ./.build/debug/Dealer
♠︎6
♢K
♢2
♡8
♠︎7
♣︎10
♣︎5
♢A
♡Q
♡7

The complete code for the Dealer package can be found at
https://github.com/apple/example-package-dealer.


For more information about using the Swift Package Manager,
see the documentation provided in the Swift Package Manager project on GitHub.

Swift Package Manager Project

The Swift Package Manager is a tool for managing distribution of source code, aimed at making it easy to share your code and reuse others’ code. The tool directly addresses the challenges of compiling and linking Swift packages, managing dependencies, versioning, and supporting flexible distribution and collaboration models.

We’ve designed the system to make it easy to share packages on services like GitHub, but packages are also great for private personal development, sharing code within a team, or at any other granularity.

Swift Package Manager includes a build system that can build for macOS and Linux. Starting with Xcode 11, Xcode integrates with SwiftPM to provide support for including packages in iOS, macOS, watchOS, and tvOS applications.

The SourceKit-LSP project leverages libSwiftPM and provides Language Server Protocol implementation for editors that support LSP.


Table of Contents

  • Getting Started
  • Documentation
  • System Requirements
  • Installation
  • Contributing
  • Reporting issues
  • License

Getting Started

Please use this guide for learning package manager basics.


Documentation

For Quick Help use the swift package --help command.

For documentation on using Swift Package Manager, creating packages, and more, see the documentation directory.

For documentation on developing the Swift Package Manager itself, see the contribution guide.

For detailed documentation on the package manifest API, see PackageDescription API.

For release notes with information about changes between versions, see the release notes.


System Requirements

The package manager’s system requirements are the same as those for Swift with the caveat that the package manager requires Git at runtime as well as build-time.


Installation

The package manager is available as part the Swift toolchains available on Swift.org) including snapshots for the latest versions built from main branch. For installation instructions for downloaded snapshots, please see the Getting Started section of Swift.org.

The Swift Package Manager is also included in Xcode 8.0 and all subsequent releases.

You can verify your installation by typing swift package --version in a terminal:

$ swift package --version
Apple Swift Package Manager - ...

Contributing

There are several ways to contribute to Swift Package Manager. To learn about the policies, best practices that govern contributions to the Swift project and instructions for setting up the development environment please read the Contributor Guide.

The Swift package manager uses llbuild as the underlying build system for compiling source files. It is also open source and part of the Swift project.


Reporting issues

If you have any trouble with the package manager, help is available. We recommend:

  • The Swift Forums,
  • SwiftPM’s bug tracker

When reporting an issue please follow the bug reporting guidelines, they can be found in contribution guide.

If you’re not comfortable sharing your question with the list, contact details for the code owners can be found in CODEOWNERS; however, Swift Forums is usually the best place to go for help.


License

Copyright 2015 — 2024 Apple Inc. and the Swift project authors. Licensed under Apache License v2.0 with Runtime Library Exception.

See https://swift.org/LICENSE.txt for license information.

See https://swift.org/CONTRIBUTORS.txt for Swift project authors.

Swift is a modern, high-performance programming language developed by Apple, designed to give developers the ability to create powerful, modern apps with a clean and easy-to-read syntax. Initially introduced for developing iOS, macOS, watchOS, and tvOS apps, Swift has since evolved to become a versatile language for a wide range of applications, including web development, cloud services, and beyond. As a Windows user, you can benefit from Swift’s capabilities, such as its high-performance compilation, modern design, and vast community support, to build robust and scalable applications.

By installing Swift on your Windows machine, you can tap into its numerous benefits, including cross-platform development, which enables you to create applications that run seamlessly across multiple operating systems. Additionally, Swift’s compatibility with popular frameworks and libraries, such as Vapor and Kitura, allows you to build fast, scalable, and secure web applications. With Swift on Windows, you can unlock new possibilities for web development, machine learning, and more.

In this article, we will provide a step-by-step guide on how to install Swift on Windows, covering the necessary tools and software required to set up a development environment that mimics the macOS ecosystem.

Downloading Swift on Windows

To download Swift for Windows machine, navigate to the official Swift website. This page provides several methods for downloading Swift, each catering to different user needs and preferences. Let’s break down each method to help you decide which one suits you best.

1. Package Manager: WinGet

The first method involves installing Swift via the Windows Package Manager (WinGet). WinGet is a command-line package manager that allows you to easily install and manage software on Windows. This method is ideal if you’re already familiar with command-line interfaces and want to manage your software packages efficiently. Refer to our guide on how to install WinGet on Windows system.

2. Package Installer (.exe)

The second method involves downloading a package installer (.exe) from the official Swift website. This method provides two architecture options:

  • Download (x86_64) for 64-bit systems
  • Download (arm64) for ARM-based systems

This method is suitable for users who prefer a more traditional installation process, where they can download and run an executable file to install the software. This approach is straightforward and easy to follow, making it a good choice for beginners.

3. Scoop

The third method involves installing Swift via Scoop, a popular package manager for Windows. Scoop allows you to easily install and manage software on your system, and it’s particularly useful for installing software that’s not available through the official Windows Store. To use Scoop, you’ll need to have it installed on your system first.

4. Docker

The fourth method involves using Docker installed on Windows images for Swift. This method is geared towards developers who are already familiar with Docker and want to use it to manage their development environments. Docker provides a containerized environment for Swift, allowing you to easily switch between different versions of the language.

Choosing the Simplest Method

For the purpose of this article, we’ll focus on the Package Installer (.exe) method, as it’s one of the simplest and most straightforward approaches. This method doesn’t require any prior knowledge of command-line interfaces or package managers, making it an excellent choice for beginners:

swift 6.0

We’ll guide you through the process of downloading and installing the Swift package installer (.exe) in the next steps.

Install Swift on Our Windows VPS!

Hosting a Windows VPS with Ultahost is now easier and faster than ever. Experience lightning-fast SSD NVMe speeds with no interruptions.

Installing Swift on Windows

Step 1: Accepting the Terms and Conditions

Once you’ve downloaded the Swift package installer (.exe), run the file to begin the installation process. The welcome screen will appear, displaying the version number of Swift, which in this case is 6.0.0. Below the version number, you’ll see a summary of the terms and conditions of using Swift:

swift developer kit

Before proceeding, it’s essential to read and understand the terms and conditions of using Swift. The terms and conditions outline the rights and responsibilities of both you (the user) and Apple (the developer of Swift).

To proceed with the installation, you must accept the terms and conditions by checking the box next to “I accept the terms in the License Agreement.” This indicates that you’ve read, understood, and agreed to the terms and conditions.

In addition to the checkbox, you’ll notice two other buttons:

  • Options: This button allows you to customize the installation process, such as specifying the installation location or choosing which components to install.
  • Cancel: This button will cancel the installation process and close the installer.

For now, we’ll proceed with the default installation settings. Make sure to check the box next to “I accept the terms in the License Agreement” and click the Install button to continue with the installation process.

Step 2: Installing Swift

Once you’ve accepted the terms and conditions, the installation process will begin automatically. However, you might notice that the installer doesn’t prompt you to specify the installation location. Instead, it will use the default installation path.

So, if you want to install Swift in a custom location, you can use the Options button to specify the installation path.  After specifying the installation location, click on the Install button to continue with the installation process.

The installer will proceed with the installation, and you’ll see the progress bar indicating the status of the installation. This may take a few minutes to complete, depending on your system’s specifications and the speed of your hard drive.

When the installation process is completed, you’ll see a confirmation message indicating that the installation has been successful:

swift installation

You can further verify the swift version via the command prompt as well. For this, you can write the below command by opening a command prompt:

swift -v
swift release

Moreover, you will also get some basic commands to get started with the swift on Windows.

Features of Swift

Swift is a modern, powerful, and versatile programming language that offers a range of features that make it an ideal choice for developers. Some of the key features of Swift include:

  1. High-performance compilation: Swift’s compiler is designed to generate high-performance machine code, making it suitable for systems programming and high-performance applications.
  2. Modern design: Swift’s syntax and design are influenced by modern programming languages, making it easy to learn and use.
  3. Memory safety: Swift’s compiler and runtime are designed to prevent common programming errors, such as null pointer dereferences and buffer overflows.
  4. Generics: Swift’s generics system allows developers to write reusable and flexible code.
  5. Closures: Swift’s closures allow developers to pass functions as arguments to other functions, making writing concise and expressive code easy.

Benefits of Using Swift

Swift offers a range of benefits to developers, including:

  • Easy to learn: Swift’s syntax and design are easy to learn, making it an ideal choice for new developers.
  • Cross-platform development: Swift can develop applications for multiple platforms, including macOS, iOS, watchOS, and tvOS.
  • High-performance applications: Swift’s high-performance compilation and execution model makes it suitable for developing high-performance applications.
  • Large community: Swift has a large and active community of developers, making it easy to find resources, tutorials, and support.
  • Constantly evolving: Swift is constantly evolving, with new features and improvements being added regularly, making it a great choice for developers who want to stay up-to-date with the latest technology.

Conclusion

In this article, we walked through installing Swift on a Windows machine. We discussed the different methods available for installation, including the package manager, package installer, Scoop, and Docker. We chose the package installer method as the most straightforward approach. We then navigated through the installation process, accepting the terms and conditions, specifying the installation location, and waiting for the installation to complete.

Overall, the installation process was relatively smooth and easy to follow. With the default installation settings, Swift was installed successfully on our Windows machine. We also discussed the features and benefits of Swift, highlighting its high-performance compilation, modern design, and cross-platform development capabilities. With Windows Swift setup, Now you’re ready to start exploring its capabilities and building your applications.

Streamline your Swift setup on Windows with Ultahost’s VPS hosting, offering powerful processing, increased memory, and ample storage. Focus on managing your projects effortlessly, while Ultahost delivers the performance and resources you need to run swift smoothly.

FAQ

Is Swift officially supported on Windows?

Yes, Swift is officially supported on Windows as of version 5.3 and later.

What are system requirements for installing Swift on Windows?

You’ll need a Windows 10 or later operating system, a 64-bit architecture, and the Windows Subsystem for Linux (WSL) or Visual Studio installed.

How do I install Swift on Windows?

You can install Swift by downloading the pre-built binaries from the official Swift website.

Do I need to install any additional tools?

Yes, installing Visual Studio is recommended for building and running Swift applications. You also need to have the C++ build tools installed.

How can I set up WSL for Swift development?

Install WSL by enabling it through Windows features, then install a Linux distribution (like Ubuntu) from the Microsoft Store. After that, you can install Swift within the WSL environment.

What commands do I use to check if Swift is installed correctly?

Open a command prompt or terminal and run swift –version. This should display the installed version of Swift.

Can I use an IDE for Swift development on Windows?

Yes, you can use Visual Studio Code with extensions for Swift or try JetBrains CLion with Swift support.

Время на прочтение9 мин

Количество просмотров36K

Вместе с релизом в open source языка Swift 3 декабря 2015 года Apple представила децентрализованный менеджер зависимостей Swift Package Manager.

К публичной версии приложили руку небезызвестные Max Howell, создатель Homebrew, и Matt Thompson, написавший AFNetworking. SwiftPM призван автоматизировать процесс установки зависимостей, а также дальнейшее тестирование и сборку проекта на языке Swift на всех доступных операционных системах, однако пока его поддерживают только macOS и Linux. Если интересно, идите под кат.

Минимальные требования – Swift 3.0. Чтобы открыть файл проекта потребуется Xcode 8.0 или выше. SwiftPM позволяет работать с проектами без xcodeproj-файла, поэтому Xcode на OS X не обязателен, а на Linux его и так нет.

Стоит развеять сомнения – проект еще в активной разработке. Использование UIKit, AppKit и других фреймворков iOS и OS X SDK как зависимостей недоступно, так как SwiftPM подключает зависимости в виде исходного кода, который потом собирает. Таким образом, использование SwiftPM на iOS, watchOS и tvOS возможно, но только с использованием Foundation и зависимостей сторонних библиотек из открытого доступа. Один единственный import UIKit делает вашу библиотеку непригодной для распространения через SwiftPM.

Все примеры в статье написаны с использованием версии 4.0.0-dev, свою версию можете проверить с помощью команды в терминале

swift package —version

Идеология Swift Package Manager

Для работы над проектом больше не нужен файл *.xcodproj — теперь его можно использовать как вспомогательный инструмент. Какие файлы участвуют в сборке модуля, зависит от их расположения на диске — для SwiftPM важны имена директорий и их иерархия внутри проекта. Первоначальная структура директории проекта выглядит следующим образом:

  • Sources – исходные файлы для сборки пакета, разбитые внутри по директориям продуктов – для каждого продукта отдельная папка.
  • Tests – тесты для разрабатываемого продукта, разбивка на папки аналогично папке Sources.
  • Package.swift – файл с описанием пакета.
  • README.md – файл документации к пакету.

Внутри папок Sources и Tests SwiftPM рекурсивно ищет все *.swift-файлы и ассоциирует их с корневой папкой. Чуть позже мы создадим подпапки с файлами.

Основные компоненты

Теперь давайте разберемся с основными компонентами в SwiftPM:

  • Модуль (Module) – набор *.swift–файлов, выполняющий определенную задачу. Один модуль может использовать функционал другого модуля, который он подключает как зависимость. Проект может быть собран на основании единственного модуля. Разделение исходного кода на модули позволяет выделить в отдельный модуль функцию, которую можно будет использовать повторно при сборке другого проекта. Например, модуль сетевых запросов или модуль работы с базой данных. Модуль использует порог инкапсуляции уровня internal и представляет собой библиотеку (library), которая может быть подключена к проекту. Модуль может быть подключен как из того же самого пакета (представлен в виде другого таргета), так и из другого пакета (представлен в виде другого продукта).
  • Продукт (Product) – результат сборки таргета (target) проекта. Это может быть библиотека (library) или исполняемый файл (executable). Продукт включает себя исходный код, который относится непосредственно к этому продукту, а также исходный код модулей, от которых он зависит.
  • Пакет (Package) – набор *.swift–файлов и manifest-файла Package.swift, который определяет имя пакета и набор исходных файлов. Пакет содержит один или несколько модулей.
  • Зависимость (Dependency) – модуль, необходимый для исходного кода в пакете. У зависимости должен быть путь (относительный локальный или удаленный на git-репозиторий), версия, перечень зависимостей. SwiftPM должен иметь доступ к исходному коду зависимости для их компиляции и подключения к основному модулю. В качестве зависимости таргета может выступать таргет из того же пакета или из пакета-зависимости.

Получаем, что зависимости выстраиваются в граф – у каждой зависимости могут быть свои собственные и так далее. Разрешение графа зависимостей – основная задача менеджера зависимостей.

Замечу, что все исходные файлы должны быть написаны на языке Swift, возможности использовать язык Objective-C – нет.

Каждый пакет должен быть самодостаточным и изолированным. Его отладка производится не посредством запуска (run), а с помощью логических тестов (test).

Далее рассмотрим простой пример с подключением к проекту зависимости Alamofire.

Разработка тестового проекта

Перейдем через терминал в папку, где будет лежать наш проект, создадим для него директорию и перейдем в нее.

mkdir IPInfoExample
cd IPInfoExample/

Далее инициализируем пакет с помощью команды

swift package init

В результате создается следующая иерархия исходных файлов


├── Package.swift
├── README.md
├── Sources
│   └── IPInfoExample
│       └── main.swift
└── Tests
     └── IPInfoExampleTests
         ├ LinuxMain.swift
         └── IPInfoExampleTests
             └── IPInfoExampleTests.swift

В условиях отсутствия индекса файла проекта *.xcodeproj менеджеру зависимостей нужно знать, какие исходные файлы должны участвовать в процессе сборки и в какие таргеты их включать. Поэтому SwiftPM определяет строгую иерархию папок и перечень файлов:

  • Package-файл;
  • README-файл;
  • Папка Sources с исходными файлами – отдельная папка для каждого таргета;
  • Папка Tests – отдельная папка для каждого тестового таргета.

Уже сейчас можем выполнить команды


swift build
swift test

для сборки пакета или для запуска теста Hello, world!

Добавление исходных файлов

Создадим файл Application.swift и положим его в папку IPInfoExample.

public struct Application {}

Выполняем swift build и видим, что в модуле уже компилируется 2 файла.

Compile Swift Module 'IPInfoExample' (2 sources)

Создадим директорию Model в папке IPInfoExample, создадим файл IPInfo.swift, а файл IPInfoExample.swift удалим за ненадобностью.


//Используем протокол Codable для маппинга JSON в объект
public struct IPInfo: Codable { 
    let ip: String

    let city: String

    let region: String

    let country: String
}

После этого выполним команду swift build для проверки.

Добавление зависимостей

Откроем файл Package.swift, содержание полно описывает ваш пакет: имя пакета, зависимости, таргет. Добавим зависимость Alamofire.

// swift-tools-version:4.0
import PackageDescription // Модуль, в котором находится описание пакета

let package = Package(
    name: "IPInfoExample", // Имя нашего пакета
    products: [
        .library(
            name: "IPInfoExample",
            targets: ["IPInfoExample"]),
    ],
    dependencies: [
        // подключаем зависимость-пакет Alamofire, указываем ссылку на GitHub
        .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.0.0") 
    ],
    targets: [
        .target(
            name: "IPInfoExample",
            // указываем целевой продукт – библиотеку, которая зависима 
            // от библиотеки Alamofire
            dependencies: ["Alamofire"]), 
        .testTarget(
            name: "IPInfoExampleTests",
            dependencies: ["IPInfoExample"]),
    ]
)

Далее снова swift build, и наши зависимости скачиваются, создается файл Package.resolved c описанием установленной зависимости (аналогично Podfile.lock).

В случае если в вашем пакете только один продукт, можно использовать одинаковые имена для имени пакета, продукта и таргета. У нас это IPInfoExample. Таким образом, описание пакета можно сократить, опустив параметр products. Если заглянуть в описание пакета Alamofire, увидим, что там не описаны таргеты. По умолчанию создаются один таргет с именем пакета и файлами исходного кода из папки Sources и один таргет с файлом-описанием пакета (PackageDescription). Тестовый таргет при использовании SwiftPM не задействуется, поэтому папка с тестами исключается.


import PackageDescription

let package = Package(name: "Alamofire", dependencies : [], exclude: [“Tests"])

Чтобы удостовериться в правильности создания модулей, таргетов, продукта, можем выполнить команду

swift package describe

В результате для Alamofire получим следующий лог:


Name: Alamofire
Path: /Users/ivanvavilov/Documents/Xcode/Alamofire
Modules:
    Name: Alamofire
    C99name: Alamofire
    Type: library
    Module type: SwiftTarget
    Path: /Users/ivanvavilov/Documents/Xcode/Alamofire/Source
    Sources: AFError.swift, Alamofire.swift, DispatchQueue+Alamofire.swift, MultipartFormData.swift, NetworkReachabilityManager.swift, Notifications.swift, ParameterEncoding.swift, Request.swift, Response.swift, ResponseSerialization.swift, Result.swift, ServerTrustPolicy.swift, SessionDelegate.swift, SessionManager.swift, TaskDelegate.swift, Timeline.swift, Validation.swift

Если у пакета несколько продуктов, то в качестве зависимости мы указываем пакет зависимости, а уже в зависимости таргета указываем зависимость от модуля пакета. Например, так подключен SourceKitten в нашей библиотеке Synopsis.

import PackageDescription
let package = Package(
    name: "Synopsis",
    products: [
        Product.library(
            name: "Synopsis",
            targets: ["Synopsis"]
        ),
    ],
    dependencies: [
        Package.Dependency.package(
            // зависимость от пакета SourceKitten
            url: "https://github.com/jpsim/SourceKitten", 
            from: "0.18.0"
        ),
    ],
    targets: [
        Target.target(
            name: "Synopsis",
            // зависимость от библиотеки SourceKittenFramework
            dependencies: ["SourceKittenFramework"] 
        ),
        Target.testTarget(
            name: "SynopsisTests",
            dependencies: ["Synopsis"]
        ),
    ]
)

Так выглядит описание пакета SourceKitten. В пакете описаны 2 продукта


.executable(name: "sourcekitten", targets: ["sourcekitten"]),
.library(name: "SourceKittenFramework", targets: ["SourceKittenFramework"])

Synopsis использует продукт-библиотеку SourceKittenFramework.

Создание файла проекта

Мы можем создать файл проекта для своего удобства, выполнив команду

swift package generate-xcodeproj

и в результате получим в корневой папке проекта файл IPInfoExample.xcodeproj.
Открываем его, видим все исходники в папке Sources, в том числе с подпапкой Model, и исходники зависимостей в папке Dependencies.

Важно отметить, что данный шаг является опциональным при разработке продукта и не влияет на механизм работы SwiftPM. Заметьте, что все исходные файлы располагаются так же, как и на диске.

Проверка подключенной зависимости

Проверим, корректно ли подключилась зависимость. В примере делаем асинхронный запрос к сервису ipinfo для получения данных о текущем ip-адресе. JSON ответа декодируем в модельный объект – структуру IPInfo. Для простоты примера не будем обрабатывать ошибку маппинга JSON или ошибку сервера.


// импортируем библиотеку так же, как при использовании cocoapods или carthage 
import Alamofire 
import Foundation

public typealias IPInfoCompletion = (IPInfo?) -> Void

public struct Application {
    
    public static func obtainIPInfo(completion: @escaping IPInfoCompletion) {
        Alamofire
            .request("https://ipinfo.io/json")
            .responseData { result in
                var info: IPInfo?
                if let data = result.data {
                    // Маппинг JSON в модельный объект
                    info = try? JSONDecoder().decode(IPInfo.self, from: data)
                }
                completion(info)
        }
    }
    
}

Далее можем воспользоваться командой build в Xcode, а можем выполнить команду swift build в терминале.

Проект с исполняемым файлом

Выше описан пример для инициализации проекта библиотеки. SwiftPM позволяет работать с проектом исполняемого файла. Для этого при инициализации используем команду

swift package init —type executable.

Привести текущий проект к такому виду также можно, создав файл main.swift в директории Sources/IPInfoExample. При запуске исполняемого файла main.swift является точкой входа.
Напишем в него одну строчку

print("Hello, world!”)

А затем выполним команду swift run, в консоль выведется заветное предложение.

Синтаксис описания пакета

Описание пакета в общем виде выглядит следующим образом:


Package(
    name: String,
    pkgConfig: String? = nil,
    providers: [SystemPackageProvider]? = nil,
    products: [Product] = [],
    dependencies: [Dependency] = [],
    targets: [Target] = [],
    swiftLanguageVersions: [Int]? = nil
)

  • name – имя пакета. Единственный обязательный аргумент для пакета.
  • pkgConfig – используется для пакетов модулей, установленных в системе (System Module Packages), определяет имя pkg-config-файла.
  • providers – используется для пакетов системных модулей, описывает подсказки для установки недостающих зависимостей через сторонние менеджеры зависимостей – brew, apt и т.д.


import PackageDescription
let package = Package(
    name: "CGtk3",
    pkgConfig: "gtk+-3.0",
    providers: [
        .brew(["gtk+3"]),
        .apt(["gtk3"])
    ]
)

  • products – описание результата сборки таргета проекта – исполняемый файл или библиотека (статическая или динамическая).


let package = Package(
    name: "Paper",
    products: [
        .executable(name: "tool", targets: ["tool"]),
        .library(name: "Paper", targets: ["Paper"]),
        .library(name: "PaperStatic", type: .static, targets: ["Paper"]),
        .library(name: "PaperDynamic", type: .dynamic, targets: ["Paper"])
    ],
    targets: [
        .target(name: "tool")
        .target(name: "Paper")
    ]
)

Выше в пакете описано 4 продукта: исполняемый файл из таргета tool, библиотека Paper (SwiftPM выберет тип автоматически), статическая библиотека PaperStatic, динамическая PaperDynamic из одного таргета Paper.

  • Dependencies – описание зависимостей. Необходимо указать путь (локальный или удаленный) и версию.

    Управление версиями в SwiftPM происходит через git-тэги. Само версионирование можно настроить достаточно гибко: зафиксировать версию языка, git-ветки, минимальную мажорную, минорную версию пакета или хэш коммита. Опционально к тэгам добавляется суффикс вида @swift-3, таким образом можно поддерживать старые версии. Например, с версиями вида 1.0@swift-3, 2.0, 2.1 для SwiftPM версии 3 будет доступна только версия 1.0, для последней версии 4 – 2.0 и 2.1.
    Также есть возможность указать поддержку версии SwiftPM для manifest-файла, указав суффикс в имени package@swift-3.swift. Указание версии можно заменить на ветку или хэш коммита.


// 1.0.0 ..< 2.0.0
.package(url: "/SwiftyJSON", from: "1.0.0"),
// 1.2.0 ..< 2.0.0
.package(url: "/SwiftyJSON", from: "1.2.0"),
// 1.5.8 ..< 2.0.0
.package(url: "/SwiftyJSON", from: "1.5.8"),
// 1.5.8 ..< 2.0.0
.package(url: "/SwiftyJSON", .upToNextMajor(from: "1.5.8")),
// 1.5.8 ..< 1.6.0
.package(url: "/SwiftyJSON", .upToNextMinor(from: "1.5.8")),
// 1.5.8
.package(url: "/SwiftyJSON", .exact("1.5.8")),
// Ограничение версии интервалом.
.package(url: "/SwiftyJSON", "1.2.3"..<"1.2.6"),
// Ветка или хэш коммита.
.package(url: "/SwiftyJSON", .branch("develop")),
.package(url: "/SwiftyJSON", .revision("e74b07278b926c9ec6f9643455ea00d1ce04a021"))

  • targets – описание таргетов. В примере объявляем 2 таргета, второй – для тестов первого, в зависимостях указываем тестируемый.


let package = Package(
    name: "FooBar",
    targets: [
        .target(name: "Foo", dependencies: []),
        .testTarget(name: "Bar", dependencies: ["Foo"])
    ]
)

  • swiftLanguageVersions – описание поддерживаемой версии языка. Если установлена версия [3], компиляторы swift 3 и 4 выберут версию 3, если версия [3, 4] компилятор swift 3 выберет третью версию, компилятор swift 4 — четвертую.

Индекс команд

swift package init //инициализация проекта библиотеки
swift package init --type executable //инициализация проекта исполняемого файла
swift package --version //текущая версия SwiftPM
swift package update //обновить зависимости
swift package show-dependencies //вывод графа зависимостей
swift package describe // вывод описания пакета

Ресурсы

  • Пример Тестового проекта
  • Swift.org – Package Manager
  • Swift Package Manager – Usage

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows server 2012 неактивированный
  • Установка windows 11 на ноутбук без tpm
  • Nebviewer windows exe что это
  • Джакарта драйвер windows 10
  • Включить протокол smb1 windows 10 powershell