Back to Swift Reference Ask BeeAI
🔶 Swift LanguageIntermediateSwift 1.0+
Generics
Write reusable, type-safe code with generic functions, types and where constraints.
Generics let one implementation work with many types while keeping full type safety. Swift's Array, Dictionary and Optional are all generic.
Constrain generic parameters with protocols (T: Comparable) or where clauses to unlock the operations you need.
generics.swift
1struct Stack<Element> {
2 private var items: [Element] = []
3 mutating func push(_ item: Element) { items.append(item) }
4 mutating func pop() -> Element? { items.popLast() }
5}
6
7func largest<T: Comparable>(_ values: [T]) -> T? {
8 values.max()
9}
10
11var stack = Stack<String>()
12stack.push("SwiftUI")
13print(largest([3, 9, 4]) ?? 0) // 9Common pitfalls
- Do not reach for generics too early — start concrete, then generalize when a second use appears.
Still unclear? Ask BeeAI about Generics.
Get a tailored explanation, or paste your own code for a Swift 6 review. Free members get daily questions — Pro is unlimited.
Become a Founding Pro member: unlimited BeeAI, upcoming Swift paths and every new reference entry first.
See Pro Plans