Tools
Log in
English

Learn to codeSwift

Swift project structure

Based on Swift 6.4

Get a Swift package (Package.swift, Sources, Tests) or SwiftUI MVVM app zip.

Make a Swift project skeleton

Choose what to build and a code style; the folder tree, file notes and layer picture follow. Command-line tools and libraries build straight from the zip with swift build; the SwiftUI app is a set of files you add after creating a new project in Xcode.

Build a
Code style
Tests

Folder tree 6 files

  • Sources/
    • Hello/
    • HelloCLI/
  • Tests/HelloTests/

Package.swift

The package manifest. The first-line comment picks the Swift version (6.0 in the modern style means Swift 6 language mode). products are what the package offers (a command or a library); targets are the modules and tests. Each target name must match its folder under Sources/.

// swift-tools-version: 6.0import PackageDescription let package = Package(    name: "hello-app",    products: [        .executable(name: "hello-app", targets: ["HelloCLI"]),    ],    targets: [        .target(name: "Hello"),        .executableTarget(name: "HelloCLI", dependencies: ["Hello"]),        .testTarget(name: "HelloTests", dependencies: ["Hello"]),    ])

Layers

Versions written in the files Checked with the Swift 6.4 toolchain · swift-tools-version 6.0 · 5.9 · Swift Testing and XCTest (bundled with the toolchain) · App: iOS 17 (modern) · iOS 16 (classic). No outside packages are used, so there is nothing to download. Swift Testing and XCTest ship with the toolchain. The SwiftUI app comes as files to add, without an Xcode project file.

Where things go in a Swift package and an Xcode app

PathWhat goes there
Package.swiftThe package manifest. The first line, // swift-tools-version:, picks the Swift version; below it, products and targets (modules) are written in Swift.
Sources/One folder per target (Sources/Hello/). The folder name is the module name, and every .swift file inside is included without listing it.
Tests/Test targets (Tests/HelloTests/). @testable import Hello reaches even internal code; run them with swift test.
.build/Build output and intermediate files. They come back after a rebuild, so keep them out of git.
App folderAn Xcode app keeps the @main App file, screens (Views), models and Assets.xcassets in a folder named after the app. Project settings live in the .xcodeproj that Xcode creates.
Info · signingApp name, bundle ID and permission texts are set in the Xcode target settings. Letting Xcode manage them is safer than hand-written settings files.

If the command-line entry file is named main.swift, its top-level code runs first; with any other name, execution starts at static func main() of the type marked @main.

Splitting into layers

Separate input and output (arguments, screens), rules and storage. In a SwiftUI app the View calls the ViewModel, which calls a store behind a protocol, never the other way round. This layout is called MVVM (Model, View, ViewModel).

Views only draw and receive taps; the ViewModel, an @Observable class, owns screen state and actions. With the store behind a protocol, tests swap in an in-memory version.

  • The View passes taps to ViewModel methods and redraws changed values.
  • The ViewModel decides the rules. It does not import SwiftUI, so it is easy to test (even on Linux).
  • Models are plain structs; the store hides how data is kept behind a protocol.

Naming

Module and target names capitalize each word (Hello, TodoKit). Package and command names may use lowercase and - (hello-app). Test targets add Tests.

  • Types (struct, class, enum, protocol) use UpperCamelCase (TaskItem); variables, functions and parameters use lowerCamelCase (leftCount).
  • Name protocols after an ability with -able (Equatable) or after what they are with a noun (TaskStore).
  • Avoid existing module names such as Swift, Foundation, SwiftUI or XCTest; a clash makes import confusing.

SwiftUI screen examples

SwiftUI is the screen framework that runs on Apple devices (iPhone, iPad, Mac). Our server runs Linux, which has no SwiftUI, so these examples were not run; instead of output you get a picture we drew of how the screen looks. The syntax was checked with Swift 6.4.

@State · a screen that changes when tapped

When a value marked @State changes, SwiftUI calls body again and redraws. The buttons only change cups; no code updates the text or the bar by hand.

#Preview shows the screen in the Xcode preview canvas. The picture shows the screen after tapping +1 cup three times.

import SwiftUI struct WaterView: View {    @State private var cups = 0    let goal = 8     var body: some View {        VStack(spacing: 16) {            Text("Water today")                .font(.headline)            Text("\(cups) / \(goal) cups")                .font(.largeTitle.bold())            ProgressView(value: Double(cups), total: Double(goal))            HStack {                Button("Reset") {                    cups = 0                }                .buttonStyle(.bordered)                Button("+1 cup") {                    cups = min(cups + 1, goal)                }                .buttonStyle(.borderedProminent)            }        }        .padding()    }} #Preview {    WaterView()}
Drawing of the water screen: Water today, 3 / 8 cups, a progress bar, and Reset and +1 cup buttons
How it looks (our drawing)

@Observable · separating the ViewModel from the screen (MVVM)

The chore list and the count of chores left belong to an @Observable class (the ViewModel); the screen only draws them. Tapping a row calls toggle, and SwiftUI, seeing the change, redraws that row and the title. @Observable needs iOS 17 or macOS 14.

The ViewModel part (Chore and ChoreListModel) does not use SwiftUI, so we ran it on our server: 2 chores left at first, 1 after tapping the first row. The picture shows the starting screen.

import SwiftUIimport Observation struct Chore: Identifiable {    let id = UUID()    let title: String    var done = false} @Observablefinal class ChoreListModel {    var chores = [        Chore(title: "Water plants"),        Chore(title: "Take out trash", done: true),        Chore(title: "Feed the cat"),    ]     var left: Int {        chores.filter { !$0.done }.count    }     func toggle(_ chore: Chore) {        guard let i = chores.firstIndex(where: { $0.id == chore.id }) else {            return        }        chores[i].done.toggle()    }} struct ChoreListView: View {    @State private var model = ChoreListModel()     var body: some View {        NavigationStack {            List(model.chores) { chore in                Button {                    model.toggle(chore)                } label: {                    Label(chore.title, systemImage: chore.done ? "checkmark.circle.fill" : "circle")                }            }            .navigationTitle("Chores (\(model.left) left)")        }    }}
Drawing of the chore list: title Chores (2 left), rows Water plants, Take out trash (checked) and Feed the cat
How it looks (our drawing)

Four common design patterns and dependency injection

When to use each matters more than the name. All of this code was compiled and run with Swift 6.4.

Singleton · when there must be exactly one

For objects like app settings that must exist once in the whole program. init is private, so the only way in is static let shared, which is created once, on first use, safely across tasks.

In Swift 6, a singleton with changing state gets @MainActor so only the main actor touches it. Singletons make testing harder, so use them sparingly.

Settings.shared.theme = "dark"let again = Settings.sharedprint(again.theme)print(again === Settings.shared) @MainActorfinal class Settings {    static let shared = Settings()     var theme = "light"     private init() {}}

Output

darktrue

Factory · deciding what to create in one place

A static func that looks at the file extension and returns the right saver, throwing for unknown ones. Callers only know they get an any PhotoSaver. A case-less enum works well as a namespace for such functions.

for file in ["cover.png", "trip.jpg", "scan.gif"] {    do {        let saver = try SaverFactory.make(for: file)        print("\(file): \(saver.describe())")    } catch {        print("\(file): \(error)")    }} protocol PhotoSaver {    func describe() -> String} struct PNGSaver: PhotoSaver {    func describe() -> String { "lossless" }} struct JPEGSaver: PhotoSaver {    let quality: Int     func describe() -> String { "quality \(quality)" }} enum SaverError: Error {    case unknown(String)} enum SaverFactory {    static func make(for file: String) throws -> any PhotoSaver {        let ext = file.split(separator: ".").last.map(String.init) ?? ""        switch ext {        case "png":            return PNGSaver()        case "jpg", "jpeg":            return JPEGSaver(quality: 80)        default:            throw SaverError.unknown(ext)        }    }}

Output

cover.png: losslesstrip.jpg: quality 80scan.gif: unknown("gif")

Strategy · swappable ways to calculate

Pull the travel-time calculation into a protocol and pick one at the call site. Simple rules can be wrapped in a closure ({ km in ... }). some RouteStrategy means "one concrete type that conforms to this protocol".

let trip = RoutePlanner(km: 3)print(trip.minutes(by: Walking()))print(trip.minutes(by: Cycling()))print(trip.minutes(by: Custom { km in Int(km * 3) + 5 })) protocol RouteStrategy {    func minutes(for km: Double) -> Int} struct Walking: RouteStrategy {    func minutes(for km: Double) -> Int { Int(km * 15) }} struct Cycling: RouteStrategy {    func minutes(for km: Double) -> Int { Int(km * 4) }} struct Custom: RouteStrategy {    let rule: (Double) -> Int     func minutes(for km: Double) -> Int { rule(km) }} struct RoutePlanner {    let km: Double     func minutes(by strategy: some RouteStrategy) -> Int {        strategy.minutes(for: km)    }}

Output

451214

Observer · telling others when something happens

Keep listeners as an array of closures and call them in didSet. The closures are stored for later, so the parameter needs @escaping. In a SwiftUI app, @Observable does this job and redraws the screen (see the SwiftUI examples below).

let room = Thermostat()room.onChange { print("display: \($0) C") }room.onChange { print("log: changed to \($0)") }room.target = 22 final class Thermostat {    private var listeners: [(Int) -> Void] = []     var target = 20 {        didSet {            listeners.forEach { $0(target) }        }    }     func onChange(_ listener: @escaping (Int) -> Void) {        listeners.append(listener)    }}

Output

display: 22 Clog: changed to 22

Dependency injection · receiving what you need from outside

Greeter does not create its clock; it receives one through init. The real app passes the device clock, and a test passes a fake that always gives the same hour (FixedClock), so both greetings can be checked at once.

In SwiftUI, objects received this way are often handed down the view tree with .environment(...).

let morning = Greeter(clock: FixedClock(fixed: 9))let later = Greeter(clock: FixedClock(fixed: 15))print(morning.greet("Mina"))print(later.greet("Mina")) protocol Clock {    func hour() -> Int} struct FixedClock: Clock {    let fixed: Int     func hour() -> Int { fixed }} struct Greeter {    let clock: any Clock     func greet(_ name: String) -> String {        clock.hour() < 12 ? "Good morning, \(name)" : "Good afternoon, \(name)"    }}

Output

Good morning, MinaGood afternoon, Mina

Check yourself

Question 1

Which folder stays out of git?

Show the answer

Answer: 3. .build/ .build/ holds what swift build produces. List it in .gitignore; whoever clones the repository builds again.

Question 2

In a Swift package, what decides the module name you write after import?

Show the answer

Answer: 1. The target name (= the folder under Sources) The target name is the module name, and its code lives in Sources/<target name>/. The package name (hello-app) only names the package as a whole.

Questions people ask

How do I build the zip I downloaded?

For the command-line tool and the library, run swift build in the top folder and swift test for the tests. Run the tool with swift run name mina. README.md in the zip lists every command.

Why is there no .xcodeproj in the SwiftUI app zip?

Xcode project files are safest when Xcode creates them, so none is included. Create a new App project in Xcode and drag the files from the zip in. README.md lists the steps.

Should I pick the modern or the classic style?

For new work, the modern style (Swift 6, Swift Testing, @Observable). Pick classic (Swift 5, XCTest, ObservableObject) when you must support iOS 16 or match older code.