Swift: More snippets – code examples
Hello World
print("Hello World!")print outputs text: no main, no braces around the block, no semicolon. Run it with swift hallo.swift.
Variables and types
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
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
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.75Higher-order functions process collections without loops and helper variables. reduce(0, +) passes the operator as a function.
Reading and writing a file
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
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
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
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 trueExtensions add methods and computed properties, but not stored properties.
SwiftUI counter
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
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
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 = nilWithout [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
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.