0
0
Swiftprogramming~5 mins

Project structure and Swift Package Manager basics

Choose your learning style9 modes available
Introduction

Organizing your Swift code helps keep things neat and easy to find. Swift Package Manager (SPM) helps you manage your code and its parts automatically.

When you want to share your Swift code with others easily.
When your project grows and you need to keep files organized.
When you want to add external code libraries to your project.
When you want to build and test your Swift code from the command line.
When you want to manage multiple Swift modules in one place.
Syntax
Swift
swift package init --type executable

// Folder structure created:
// MyPackage/
// ├── Package.swift
// ├── Sources/
// │   └── MyPackage/
// │       └── main.swift
// └── Tests/
//     └── MyPackageTests/
//         └── MyPackageTests.swift

Package.swift is the main file that describes your package.

Sources/ folder holds your Swift code files.

Examples
This creates a Swift package for a library instead of an executable program.
Swift
swift package init --type library
This command builds your Swift package and compiles the code.
Swift
swift build
This runs all tests in the Tests/ folder to check your code.
Swift
swift test
Sample Program

This simple Swift package prints a greeting. The Package.swift file tells Swift Package Manager about the package name and where the code lives. The main.swift file contains the code that runs.

Swift
// Package.swift
// This file defines the package and its settings

// swift-tools-version:5.7
import PackageDescription

let package = Package(
    name: "HelloSPM",
    targets: [
        .executableTarget(
            name: "HelloSPM",
            path: "Sources/HelloSPM"
        )
    ]
)

// Sources/HelloSPM/main.swift
print("Hello, Swift Package Manager!")
OutputSuccess
Important Notes

You can add dependencies in Package.swift to use other packages.

SPM automatically creates a build folder to keep compiled files separate.

Use clear folder names inside Sources/ if you have multiple targets.

Summary

Swift Package Manager helps organize and build Swift projects easily.

The Package.swift file is the heart of your package setup.

Use commands like swift build and swift test to work with your package.