What are Swift generics?
Answer
Generics allow writing flexible, reusable functions and types that work with any type, subject to defined constraints. They enable type-safe code without code duplication. Generic function: func swap<T>(_ a: inout T, _ b: inout T) { let temp = a; a = b; b = temp } var x = 5, y = 10 swap(&x, &y) // x=10, y=5 var s1 = "hello", s2 = "world" swap(&s1, &s2) // Works with any type!. Generic type: struct Stack<Element> { private var items: [Element] = [] mutating func push(_ item: Element) { items.append(item) } mutating func pop() -> Element? { return items.popLast() } var top: Element? { items.last } } var intStack = Stack<Int>() intStack.push(1); intStack.push(2) var stringStack = Stack<String>(). Type constraints: func findMax<T: Comparable>(_ array: [T]) -> T? { array.max() } // Multiple constraints: func process<T: Hashable & Equatable>(_ items: [T]) { }. Associated types in protocols: protocol Queue { associatedtype Element mutating func enqueue(_ item: Element) mutating func dequeue() -> Element? }. Where clauses: func merge<T: Sequence, U: Sequence>(_ a: T, _ b: U) -> [T.Element] where T.Element == U.Element { }. Opaque types (some): func makeContainer() -> some Container { // Return type is hidden }. Generics + protocols = Swift's powerful type system for expressing abstractions.