// Copyright (C) 2024 Gradle, Inc.
//
// Licensed under the Creative Commons Attribution-Noncommercial-ShareAlike 4.0 International License.;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

[[building_swift_projects]]
= Building Swift projects

Gradle uses a convention-over-configuration approach to building native projects.
If you are coming from another native build system, these concepts may be unfamiliar at first, but they serve a purpose to simplify build script authoring.

We will look at Swift projects in detail in this chapter, but most of the topics will apply to other supported native languages as well.
// TODO: Uncomment when Swift tutorial are released
//If you don’t have much experience with building native projects with Gradle, take a look at the Swift tutorials for step-by-step instructions on how to build various types of basic Swift projects as well as some common use cases.

[[sec:swift_introduction]]
== Introduction

The simplest build script for a Swift project applies the Swift application plugin or the Swift library plugin and optionally sets the project version:

.Applying the Swift Plugin
====
include::sample[dir="snippets/swift/basic/kotlin",files="build.gradle.kts[tags=apply-swift-plugin]"]
include::sample[dir="snippets/swift/basic/groovy",files="build.gradle[tags=apply-swift-plugin]"]
====

By applying either of the Swift plugins, you get a whole host of features:

 * `compileDebugSwift` and `compileReleaseSwift` tasks that compiles the Swift source files under _src/main/swift_ for the well-known debug and release build types, respectively.
 * `linkDebug` and `linkRelease` tasks that link the compiled Swift object files into an executable for applications or shared library for libraries with shared linkage for the debug and release build types.
 * `createDebug` and `createRelease` tasks that assemble the compiled Swift object files into a static library for libraries with static linkage for the debug and release build types.

For any non-trivial Swift project, you’ll probably have some file dependencies and additional configuration specific to _your_ project.

The Swift plugins also integrates the above tasks into the standard <<base_plugin#sec:base_tasks,lifecycle tasks>>.
The task that produces the development binary is attached to `assemble`.
By default, the development binary is the debug variant.

The rest of the chapter explains the different ways to customize the build to your requirements when building libraries and applications.

// TODO Split this to put in common with the C++
[[sec:introducing_build_variants-swift]]
== Introducing build variants

Native projects can typically produce several different binaries, such as debug or release ones, or ones that target particular platforms and processor architectures.
Gradle manages this through the concepts of _dimensions_ and _variants_.

A dimension is simply a category, where each category is orthogonal to the rest.
For example, the "build type" dimension is a category that includes debug and release.
The "architecture" dimension covers processor architectures like x86-64 and x86.

A variant is a combination of values for these dimensions, consisting of exactly one value for each dimension.
You might have a "debug x86-64" or a "release x86" variant.

Gradle has built-in support for several dimensions and several values within each dimension.
You can find a list of them in the <<plugin_reference.adoc#native_languages,native plugin reference chapter>>.

[[sec:swift_source_sets]]
== Declaring your source files

Gradle’s Swift support uses a `ConfigurableFileCollection` directly from the link:{groovyDslPath}/org.gradle.language.swift.SwiftApplication.html[application] or link:{groovyDslPath}/org.gradle.language.swift.SwiftLibrary.html[library] script block to configure the set of sources to compile.

// TODO figure this out
Libraries make a distinction between private (implementation details) and public (exported to consumer) headers.

You can also configure sources for each binary build for those cases where sources are compiled only on certain target machines.

.Sources and Swift compilation
image::swift-sourcesets-compilation.png[]

// TODO once we have the testing chapter
//Test sources are configured on each test suite script block. See <<swift_testing.adoc#swift_testing,Testing Swift projects>> chapter.

[[sec:swift_dependency_management_overview]]
== Managing your dependencies

The vast majority of projects rely on other projects, so managing your project's dependencies is an important part of building any project.
Dependency management is a big topic, so we will only focus on the basics for Swift projects here.
If you’d like to dive into the details, check out the <<getting_started_dep_man.adoc#dependency-management-in-gradle,introduction to dependency management>>.

Gradle provides support for consuming pre-built binaries from Maven repositories published by Gradle footnote:[Unfortunately, Cocoapods repositories aren’t yet supported as core features].

We will cover how to add dependencies between projects within a multi-build project.

Specifying dependencies for your Swift project requires two pieces of information:

 * Identifying information for the dependency (project path, Maven GAV)
 * What it’s needed for, e.g. compilation, linking, runtime or all of the above.

This information is specified in a `dependencies {}` block of the Swift `application` or `library` script block.
For example, to tell Gradle that your project requires library `common` to compile and link your production code, you can use the following fragment:

.Declaring dependencies
====
include::sample[dir="snippets/swift/basic/kotlin",files="build.gradle.kts[tags=swift-dependency-mgmt]"]
include::sample[dir="snippets/swift/basic/groovy",files="build.gradle[tags=swift-dependency-mgmt]"]
====

The Gradle terminology for the three elements is as follows:

 * _Configuration_ (ex: `implementation`) - a named collection of dependencies, grouped together for a specific goal such as compiling or linking a module
 * _Project reference_ (ex: `project(':common')`) - the project referenced by the specified path

You can find a more comprehensive glossary of dependency management terms <<glossary.adoc#dependency_management_terminology,here>>.

As far as configurations go, the main ones of interest are:

 * `implementation` - used for compilation, linking and runtime
 * `swiftCompile__Variant__` - for dependencies that are necessary to compile your production code but shouldn’t be part of the linking or runtime process
 * `nativeLink__Variant__` - for dependencies that are necessary to link your code but shouldn’t be part of the compilation or runtime process
 * `nativeRuntime__Variant__` - for dependencies that are necessary to run your component but shouldn’t be part of the compilation or linking process

You can learn more about these and how they relate to one another in the <<plugin_reference.adoc#native_languages,native plugin reference chapter>>.

Be aware that the <<swift_library_plugin.adoc#swift_library_plugin,Swift Library Plugin>> creates an additional configuration — `api` — for dependencies that are required for compiling and linking both the module and any modules that depend on it.

We have only scratched the surface here, so we recommend that you read the <<getting_started_dep_man.adoc#dependency-management-in-gradle,dedicated dependency management chapters>> once you’re comfortable with the basics of building Swift projects with Gradle.

Some common scenarios that require further reading include:

 * Defining a custom <<supported_repository_types.adoc#repository-types,Maven-compatible>> repository
 * Declaring dependencies with <<dependency_versions.adoc#sec:declaring-dependency-with-changing-version,changing>> (e.g. SNAPSHOT) and <<dependency_versions.adoc#sec:declaring-dependency-with-dynamic-version,dynamic>> (range) versions
 * Declaring a sibling <<declaring_dependencies_basics.adoc#sec:project-dependencies,project as a dependency>>
 * <<dependency_constraints.adoc#dependency-constraints,Controlling transitive dependencies and their versions>>
 * Testing your fixes to 3rd-party dependency via <<composite_builds.adoc#composite_builds,composite builds>> (a better alternative to publishing to and consuming from <<supported_repository_types.adoc#sec:maven-local,Maven Local>>)

You’ll discover that Gradle has a rich API for working with dependencies — one that takes time to master, but is straightforward to use for common scenarios.

[[sec:swift_compile_link]]
== Compiling and linking your code
Compiling both your code can be trivially easy if you follow the conventions:

1. Put your source code under the _src/main/swift_ directory
2. Declare your compile dependencies in the `implementation` configurations (see the previous section)
3. Run the `assemble` task

We recommend that you follow these conventions wherever possible, but you don’t have to.

There are several options for customization, as you’ll see next.

NOTE: All link:{groovyDslPath}/org.gradle.language.swift.tasks.SwiftCompile.html[SwiftCompile] tasks are incremental and cacheable.

[[sec:swift_supported_tool_chain]]
=== Supported tool chain

Gradle support the https://swift.org/download/[official Swift tool chain for macOS and Linux].
When you build a native binary, Gradle will attempt to locate a tool chain installed on your machine that can build the binary.
Gradle select the first tool chain that can build for the target operating system, architecture and Swift language support.

NOTE: For Linux users, Gradle will discover the tool chain using the system PATH.

[[sec:custom_swift_source_set_paths]]
=== Customizing file and directory locations

Imagine you are migrating a library project that follows the Swift Package Manager layout (e.g. `Sources/__ModuleName___` directory for the production code).
The conventional directory structure won’t work, so you need to tell Gradle where to find the source files.
You do that via the `application` or `library` script block.

Each component script block, as well as each binary, defines where it’s source code resides.
You can override the convention values by using the following syntax:

.Setting Swift source set
====
include::sample[dir="snippets/swift/basic/kotlin/common",files="build.gradle.kts[tags=swift-source-set]"]
include::sample[dir="snippets/swift/basic/groovy/common",files="build.gradle[tags=swift-source-set]"]
====

Now Gradle will only search directly in _Sources/Common_ for the source.

[[sec:custom_swift_compile_link]]
=== Changing compiler and linker options

Most of the compiler and linker options are accessible through the corresponding task, such as `compile__Variant__Swift`, `link__Variant__` and `create__Variant__`.
These tasks are of type link:{groovyDslPath}/org.gradle.language.swift.tasks.SwiftCompile.html[SwiftCompile], link:{groovyDslPath}/org.gradle.nativeplatform.tasks.LinkSharedLibrary.html[LinkSharedLibrary] and link:{groovyDslPath}/org.gradle.nativeplatform.tasks.CreateStaticLibrary.html[CreateStaticLibrary] respectively.
Read the task reference for an up-to-date and comprehensive list of the options.

For example, if you want to change the warning level generated by the compiler for all variants, you can use this configuration:

.Setting Swift compiler options for all variants
====
include::sample[dir="snippets/swift/basic/kotlin",files="build.gradle.kts[tags=swift-compiler-options-all-variants]"]
include::sample[dir="snippets/swift/basic/groovy",files="build.gradle[tags=swift-compiler-options-all-variants]"]
====

It’s also possible to find the instance for a specific variant through the `BinaryCollection` on the `application` or `library` script block:

.Setting Swift compiler options per variant
====
include::sample[dir="snippets/swift/basic/kotlin",files="build.gradle.kts[tags=swift-compiler-options-per-variants]"]
include::sample[dir="snippets/swift/basic/groovy",files="build.gradle[tags=swift-compiler-options-per-variants]"]
====

[[sec:select_swift_target_machines]]
=== Selecting target machines

By default, Gradle will attempt to create a Swift binary variant for the host operating system and architecture.
It is possible to override this by specifying the set of `TargetMachine` on the `application` or `library` script block:

.Setting target machines
====
include::sample[dir="snippets/swift/basic/kotlin",files="build.gradle.kts[tags=swift-select-target-machines]"]
include::sample[dir="snippets/swift/basic/groovy",files="build.gradle[tags=swift-select-target-machines]"]
====

[[sec:swift_packaging]]
== Packaging and publishing

How you package and potentially publish your Swift project varies greatly in the native world.
Gradle comes with defaults, but custom packaging can be implemented without any issues.

 * Executable files are published directly to Maven repositories.
 * Shared and static library files are published directly to Maven repositories along with a zip of the public headers.
 * For applications, Gradle also supports installing and running the executable with all of its shared library dependencies in a known location.

[[sec:cleaning_swift_build]]
== Cleaning the build

The Swift Application and Library Plugins add a `clean` task to you project by using the <<base_plugin.adoc#base_plugin,base plugin>>.
This task simply deletes everything in the `layout.buildDirectory` directory, hence why you should always put files generated by the build in there.
The task is an instance of Delete and you can change what directory it deletes by setting its `dir` property.

[[sec:building_swift_libraries]]
== Building Swift libraries

The unique aspect of library projects is that they are used (or "consumed") by other Swift projects.
That means the dependency metadata published with the binaries and headers — in the form of Gradle Module Metadata — is crucial.
In particular, consumers of your library should be able to distinguish between two different types of dependencies: those that are only required to compile your library and those that are also required to compile the consumer.

Gradle manages this distinction via the <<swift_library_plugin.adoc#swift_library_plugin,Swift Library Plugin>>, which introduces an _api_ configuration in addition to the _implementation_ once covered in this chapter.
If the types from a dependency appear as unresolved symbols of the static library or within the public headers then that dependency is exposed via your library’s public API and should, therefore, be added to the _api_ configuration.
Otherwise, the dependency is an internal implementation detail and should be added to _implementation_.

If you’re unsure of the difference between an API and implementation dependency, the <<swift_library_plugin.adoc#sec:swift_library_api_vs_implementation,Swift Library Plugin>> chapter has a detailed explanation.
In addition, you can see a basic, practical example of building a Swift library in the corresponding link:../samples/sample_building_swift_libraries.html[sample].

[[sec:building_swift_applications]]
== Building Swift applications

See the <<swift_application_plugin.adoc#swift_application_plugin,Swift Application Plugin>> chapter for more details, but here’s a quick summary of what you get:

 * `install` create a directory containing everything needed to run it
 * Shell and Windows Batch scripts to start the application

You can see a basic example of building a Swift application in the corresponding link:../samples/sample_building_swift_applications.html[sample].
