Generics write flexible, type-safe functions and types—like templates in C++ or generics in Kotlin and C#, with constraints via protocol requirements.
Generic functions and types
func swapValues<T>(_ a: inout T, _ b: inout T) {
let temp = a; a = b; b = temp
}
struct Stack<Element> {
private var items: [Element] = []
mutating func push(_ item: Element) { items.append(item) }
mutating func pop() -> Element? { items.popLast() }
}
Constraints
func max<T: Comparable>(_ a: T, _ b: T) -> T { a > b ? a : b }
Important interview questions and answers
- Q: where clauses?
A: Refine associated types on protocols—func process<C: Collection>(_ c: C) where C.Element == Int. - Q: Generics vs Any?
A: Generics preserve type information and enable optimization;Anyerases types and requires runtime casting.
Self-check
- How do you constrain a generic to Comparable?
- Can structs be generic?
Tip: Prefer generics over Any—preserves type safety and enables optimizer specialization.
Interview prep
- where clauses?
Refine generic constraints on associated types and relationships.
- Generics vs Any?
Generics preserve types; Any erases and requires casting.