Examples
Eight small Swift examples: SwiftUI, async/await, networking, persistence, error handling.
Swift — examples
EXAMPLE
// ===== 1. SwiftUI counter =====
import SwiftUI
struct CounterView: View {
@State private var count = 0
var body: some View {
VStack(spacing: 16) {
Text("Clicks: \(count)").font(.title)
Button("+1") { count += 1 }.buttonStyle(.borderedProminent)
}
.padding()
}
}
// ===== 2. List with NavigationStack =====
struct UsersView: View {
let users = ["Alex", "Sam", "Lee"]
var body: some View {
NavigationStack {
List(users, id: \.self) { name in
NavigationLink(name, destination: Text("Profile of \(name)"))
}
.navigationTitle("Users")
}
}
}
// ===== 3. Async networking =====
struct GitHubRepo: Decodable {
let name: String
let stargazers_count: Int
}
func fetchRepo() async throws -> GitHubRepo {
let url = URL(string: "https://api.github.com/repos/apple/swift")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(GitHubRepo.self, from: data)
}
// SwiftUI .task:
struct RepoView: View {
@State private var repo: GitHubRepo?
var body: some View {
Group {
if let repo { Text("\(repo.name): \(repo.stargazers_count) stars") }
else { ProgressView() }
}
.task { repo = try? await fetchRepo() }
}
}
// ===== 4. UserDefaults persistence =====
@AppStorage("theme") private var theme = "light"
struct SettingsView: View {
@AppStorage("theme") private var theme = "light"
var body: some View {
Picker("Theme", selection: $theme) {
Text("Light").tag("light")
Text("Dark").tag("dark")
}
}
}
// ===== 5. Error handling =====
enum APIError: Error { case notFound, network(Error) }
func loadUser(id: Int) async throws -> User {
do {
let (data, _) = try await URLSession.shared.data(from: URL(string: "/api/users/\(id)")!)
return try JSONDecoder().decode(User.self, from: data)
} catch let e as URLError {
throw APIError.network(e)
} catch {
throw APIError.notFound
}
}
// ===== 6. Form =====
struct SignInForm: View {
@State private var email = ""
@State private var password = ""
var canSubmit: Bool { email.contains("@") && password.count >= 8 }
var body: some View {
Form {
TextField("Email", text: $email).keyboardType(.emailAddress)
SecureField("Password", text: $password)
Button("Sign in") { /* submit */ }
.disabled(!canSubmit)
}
}
}
// ===== 7. Concurrent tasks =====
func fetchAll() async throws -> [GitHubRepo] {
async let a = fetchRepo()
async let b = fetchRepo()
return try await [a, b]
}
// ===== 8. Codable + JSON =====
struct Order: Codable {
let id: UUID
let total: Decimal
let customer: String
let createdAt: Date
enum CodingKeys: String, CodingKey {
case id, total, customer
case createdAt = "created_at"
}
}
let json = #"{"id":"...","total":49.95,"customer":"Alex","created_at":"2024-04-10T03:14:00Z"}"#
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let order = try decoder.decode(Order.self, from: Data(json.utf8))
// ===== Patterns =====
// - @State / @Observable for view state
// - .task for async work tied to view lifecycle
// - @AppStorage for small key-value persistence
// - Codable + JSONDecoder for networking
// - async/await + structured concurrency
// ===== Pitfalls =====
// - Force-unwrap (!) -> crashes
// - Long async chains without cancellation
// - Decodable mismatches (snake_case vs camelCase) without CodingKeys
// - State mutation outside main actor in SwiftUI
Why it matters
Eight small Swift examples cover the daily SwiftUI + async + Codable + persistence + form story. Memorise these shapes and you can scaffold most iOS screens in minutes.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
// Pure Swift CLI, then SwiftUI sample app, then a network + Codable refactor.Try it Yourself »
Discussion
Loading…