Swift Tutorial · Swift Projects · Lesson 29 of 30
Swift Packages, SwiftUI and Server-Side Swift
How real Swift projects are organised: Swift packages, SwiftUI apps, and Swift on the server.
Swift packages
A package is described by Package.swift, which is itself Swift code:
// swift-tools-version: 6.2
import PackageDescription
let package = Package(
name: "Shop",
platforms: [.macOS(.v15), .iOS(.v18)],
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.6.0"),
],
targets: [
.executableTarget(name: "Shop", dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
]),
.testTarget(name: "ShopTests", dependencies: ["Shop"]),
]
)
SwiftUI
SwiftUI builds Apple-platform interfaces declaratively: a view is a struct whose body describes the UI
for the current state, and SwiftUI updates the screen when @State changes. It's covered in depth in the iOS
with SwiftUI course.
import SwiftUI
struct CounterView: View {
@State private var count = 0
var body: some View {
VStack(spacing: 12) {
Text("Tapped \(count) times")
Button("Tap me") { count += 1 }
.buttonStyle(.borderedProminent)
}
.padding()
}
}
Server-side Swift
Vapor and Hummingbird are web frameworks built on SwiftNIO and async/await; Swift's low memory use and fast startup suit containers and serverless functions. Business logic is plain Swift that runs anywhere:
struct CartItem {
let name: String
let price: Double
let quantity: Int
}
func cartTotal(_ items: [CartItem], couponPercent: Double = 0) -> Double {
let subtotal = items.reduce(0) { $0 + $1.price * Double($1.quantity) }
return subtotal * (100 - couponPercent) / 100
}
let items = [CartItem(name: "mug", price: 12, quantity: 2), CartItem(name: "tea", price: 6.5, quantity: 1)]
print(cartTotal(items))
print(cartTotal(items, couponPercent: 10))
Output
30.5 27.45
Run this on your computer — see “Get Started” for setup.
Test yourself
In SwiftUI, what happens when a @State property changes?
Nothing until you call refresh()SwiftUI recomputes the view's body and updates the screenThe app restartsA new window opens
Show answer
Answer: SwiftUI recomputes the view's body and updates the screen