Introduction
Generics allow you to write flexible, reusable functions and types that can work with any type, subject to requirements you define, while still maintaining type safety. Instead of writing a separate function for swapping two Int values, two String values, and so on, a single generic function can handle all of them. Swift's standard library, including Array and Dictionary, is itself built almost entirely using generics.
Cricket analogy: A single generic "chase calculator" function works whether Virat Kohli is chasing a T20 total or Rohit Sharma is chasing an ODI target, instead of writing a separate formula for each format while still respecting the rules of each.
Syntax
func swapValues<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}Explanation
The placeholder type name T, written inside angle brackets after the function name, stands in for a real type that Swift determines when the function is called. Because both parameters a and b use the same placeholder T, the compiler enforces that both arguments must be of the same actual type, whether that is Int, String, or a custom type. Generic types work the same way, for example struct Stack<Element> { var items: [Element] = [] } defines a stack that can hold any single, consistent element type. Type constraints, such as <T: Equatable>, restrict a generic parameter to types conforming to a specific protocol, enabling operations like == inside the generic code.
Cricket analogy: Just as "Batsman" is a placeholder until you specify Kohli or Rohit at selection time, T is a placeholder type until Swift resolves it when the function is called, and both openers must bat with the same technique.
Example
struct Stack<Element> {
var items: [Element] = []
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element? {
return items.popLast()
}
}
var intStack = Stack<Int>()
intStack.push(10)
intStack.push(20)
print(intStack.pop() ?? -1)Output
20Key Takeaways
- Generics let one function or type work with any type while preserving type safety.
- Placeholder type names like T are declared in angle brackets, e.g. func swapValues<T>.
- Generic types, such as Stack<Element>, define reusable containers or structures.
- Type constraints like <T: Equatable> restrict a generic to types conforming to a given protocol.
- Generics avoid duplicating near-identical code for every concrete type.
Practice what you learned
1. What is the main benefit of using generics in Swift?
2. In func swapValues<T>(_ a: inout T, _ b: inout T), what does T represent?
3. What does the constraint <T: Equatable> mean on a generic function?
4. Which Swift standard library types are built using generics?
Was this page helpful?
You May Also Like
Protocols in Swift
Learn how Swift protocols define blueprints of methods and properties that structs, classes, and enums can conform to.
Functions in Swift
Learn how to declare, call, and label the parameters of reusable blocks of code called functions in Swift.
Arrays in Swift
Learn how Swift arrays store ordered, mutable collections of values and how to manipulate them safely.
Structs in Swift
Structs are value types in Swift that are copied on assignment and come with a free memberwise initializer.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics