SwSwift
AdvancedLesson 14 of 16

Generics & Property Wrappers – Swift

Reusable code for many types, associated types, and property wrappers.

Generics let functions and types work with placeholder types. With constraints (T: Comparable) you specify what the type must be able to do. The standard library is full of them: Array<Element>, Optional<Wrapped>, Dictionary<Key, Value>.

func groesstes<T: Comparable>(_ liste: [T]) -> T? {
    guard var g = liste.first else { return nil }
    for x in liste where x > g { g = x }
    return g
}
print(groesstes([3, 9, 2]) ?? 0, groesstes(["b", "z", "a"]) ?? "")   // 9 z

struct Stapel<Element> {
    private var elemente: [Element] = []
    mutating func push(_ x: Element) { elemente.append(x) }
    mutating func pop() -> Element? { elemente.popLast() }
    var oberstes: Element? { elemente.last }
}
var s = Stapel<String>()
s.push("a"); s.push("b")
print(s.pop() ?? "-", s.oberstes ?? "-")                             // b a

Protocols can have associated types (associatedtype), which keeps them flexible without a fixed type. Extensions can be restricted to conditions with where:

protocol Behaelter {
    associatedtype Element
    mutating func hinzufuegen(_ e: Element)
    var anzahl: Int { get }
}

extension Stapel: Behaelter {
    mutating func hinzufuegen(_ e: Element) { push(e) }
    var anzahl: Int { elemente.count }
}

extension Array where Element: Numeric {
    var summe: Element { reduce(0, +) }
}
print([1, 2, 3].summe, [1.5, 2.5].summe)                            // 6 4.0

func geradeZahlen(_ z: [Int]) -> some Collection<Int> {
    z.filter { $0 % 2 == 0 }                                        // hidden return type
}
print(geradeZahlen([1, 2, 3, 4]).count)                             // 2

A property wrapper encapsulates recurring logic for properties (@propertyWrapper). SwiftUI builds on it: @State, @Binding, and @AppStorage are property wrappers.

@propertyWrapper
struct Begrenzt {
    private var wert: Int
    let maximum: Int

    var wrappedValue: Int {
        get { wert }
        set { wert = min(newValue, maximum) }
    }
    init(wrappedValue: Int, maximum: Int) {
        self.maximum = maximum
        self.wert = min(wrappedValue, maximum)
    }
}

struct Spieler {
    @Begrenzt(maximum: 100) var leben = 100
}
var spieler = Spieler()
spieler.leben = 150
print(spieler.leben)                                                // 100
TipKey paths (\Person.name) are type-safe references to properties: personen.map(\.name), sorted(by: { $0.alter < $1.alter }). Swift 5.9 brought parameter packs (each T) and macros (@Observable, #Preview).
WarningToo many levels of generics and constraints make error messages cryptic. Keep generic code as simple as possible, and write concrete versions first before you generalize them.