SwSwift

Swift: More snippets – code examples

Contents

Hello World

Basics#print#outputCompare in all languages
Use case: A first test of whether Swift and the environment work.
print("Hello World!")

print outputs text: no main, no braces around the block, no semicolon. Run it with swift hallo.swift.

Variables and types

Basics#let#var#typeCompare in all languages
Use case: Storing values and checking their type; separating constants from mutable values.
let name = "Ada"
var alter = 36
alter += 1
let groesse = 1.68
let aktiv = true
print(name, alter, groesse, aktiv)
print(type(of: alter), type(of: groesse))

let is constant, var is mutable. Types are inferred; type(of:) displays them.

Function with a default value

Functions#func#return#labelCompare in all languages
Use case: Bundling recurring logic, e.g. greeting texts or calculations.
func begruesse(_ name: String, gruss: String = "Hello") -> String {
    "\(gruss), \(name)!"
}

print(begruesse("Ada"))
print(begruesse("Linus", gruss: "Hi"))

_ omits the argument label, while gruss: stays named. With a single expression, return is optional.

map, filter, reduce

Functions#map#filter#reduce#closure
Use case: Processing data: converting, selecting, aggregating (prices, measurements, lists).
let preise = [4.5, 12.0, 7.25, 30.0]
let teuer = preise.filter { $0 > 10 }
let mitSteuer = preise.map { ($0 * 1.19 * 100).rounded() / 100 }
let summe = preise.reduce(0, +)
print(teuer)          // [12.0, 30.0]
print(mitSteuer)      // [5.36, 14.28, 8.63, 35.7]
print(summe)          // 53.75

Higher-order functions process collections without loops and helper variables. reduce(0, +) passes the operator as a function.

Reading and writing a file

Files#file#foundation#ioCompare in all languages
Use case: Saving and loading logs, configurations, or text data.
import Foundation

let pfad = "notizen.txt"
do {
    try "Line 1\nLine 2\n".write(toFile: pfad, atomically: true, encoding: .utf8)
    let inhalt = try String(contentsOfFile: pfad, encoding: .utf8)
    for zeile in inhalt.split(separator: "\n") { print(zeile) }
} catch { print("Error:", error) }

File access is part of Foundation. Both calls can throw, hence try inside the do block. In apps you usually use FileManager and URLs.

JSON with Codable

Files#json#codable#api
Use case: Exchanging data with web APIs or files without parsing by hand.
import Foundation

struct Person: Codable { let name: String; let sprachen: [String] }

let ada = Person(name: "Ada", sprachen: ["Swift", "C"])
let daten = try JSONEncoder().encode(ada)
print(String(data: daten, encoding: .utf8)!)
let zurueck = try JSONDecoder().decode(Person.self, from: daten)
print(zurueck.sprachen[0])

Codable generates encoding and decoding automatically. If decoding fails, it throws a DecodingError; in real code use do/catch.

Protocol with a default implementation

Protocols#protocol#extension#any
Use case: Defining shared behavior for many types without inheritance (plugins, shapes, data sources).
protocol Beschreibbar {
    var titel: String { get }
}
extension Beschreibbar {
    func beschreibung() -> String { "[\(titel)]" }
}

struct Buch: Beschreibbar { let titel: String }
struct Film: Beschreibbar {
    let titel: String
    func beschreibung() -> String { "Movie: \(titel)" }
}

let liste: [any Beschreibbar] = [Buch(titel: "Swift"), Film(titel: "Matrix")]
print(liste.map { $0.beschreibung() })

Because beschreibung() is not listed as a requirement in the protocol, any Beschreibbar calls the default version, even for Film. Add the method to the protocol so that Film overrides it.

Extension for existing types

Protocols#extension#string#int
Use case: Attaching helper functions directly to standard types (e.g. string helpers in a project).
extension String {
    var wortAnzahl: Int { split(separator: " ").count }
    func wiederhole(_ n: Int) -> String { String(repeating: self, count: n) }
}
extension Int {
    var istGerade: Bool { self % 2 == 0 }
}

print("Swift is beautiful".wortAnzahl)     // 3
print("ab".wiederhole(3))                // ababab
print(7.istGerade, 10.istGerade)        // false true

Extensions add methods and computed properties, but not stored properties.

SwiftUI counter

SwiftUI#swiftui#state#view
Use case: Building a reactive interface: change the state, and the view updates itself.
import SwiftUI

struct ZaehlerView: View {
    @State private var zaehler = 0

    var body: some View {
        VStack(spacing: 12) {
            Text("Counter: \(zaehler)").font(.title)
            Button("Increment") { zaehler += 1 }
        }
        .padding()
    }
}

@State stores state and triggers a recomputation of body on change. Runs only on Apple platforms (Xcode, Preview).

HTTP request with URLSession

Networking#http#urlsession#api
Use case: Fetching data from a web API and decoding it.
import Foundation

struct Repo: Decodable { let full_name: String; let stargazers_count: Int }

let url = URL(string: "https://api.github.com/repos/swiftlang/swift")!
let (daten, antwort) = try await URLSession.shared.data(from: url)
guard (antwort as? HTTPURLResponse)?.statusCode == 200 else { exit(1) }
let repo = try JSONDecoder().decode(Repo.self, from: daten)
print(repo.full_name, repo.stargazers_count)

Cannot be run without a network. URLSession offers async variants; Decodable generates the parsing automatically. In apps, execution may need a network permission.

weak self in closures

Memory#arc#weak#closure#memory
Use case: Avoiding memory leaks caused by callbacks and timers in classes.
class Lader {
    var titel = "Report"
    var fertig: (() -> Void)?

    func starte() {
        fertig = { [weak self] in
            guard let self else { return }
            print("\(self.titel) loaded")
        }
    }
    deinit { print("Loader released") }
}

var l: Lader? = Lader()
l?.starte()
l?.fertig?()
l = nil

Without [weak self], object and closure would hold each other and deinit would never run. With weak, Lader is freed on l = nil.

Writing a unit test

Tools#test#xctest#tools
Use case: Checking functions automatically so that changes do not break anything.
import XCTest

func istGerade(_ n: Int) -> Bool { n % 2 == 0 }

final class GeradeTests: XCTestCase {
    func testGerade() {
        XCTAssertTrue(istGerade(4))
        XCTAssertFalse(istGerade(7))
        XCTAssertEqual(istGerade(0), true)
    }
}

Run it with swift test or Cmd+U in Xcode. The newer Swift Testing uses @Test and #expect(...) instead.