Generic Types
A generic type is a custom struct, class, or enum that can be built to hold any kind of value you specify, like a box that can hold anything you decide.
In this page:
Defining a Generic Struct
A generic struct declares a placeholder type that its stored properties and methods can use, letting the same struct definition work for any element type.
Example: Defining a Generic Struct
struct Box<T> {
var value: T
}
let intBox = Box(value: 42)
let stringBox = Box(value: "hello")
print(intBox.value)
print(stringBox.value)
Login to try C/C++/Java/PHP code in the editor
A Generic Stack Type
A more useful generic type, like a simple stack, defines methods that operate on its placeholder type consistently.
Example: A Generic Stack Type
struct Stack<Element> {
private var items: [Element] = []
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element? {
return items.popLast()
}
}
var stack = Stack<Int>()
stack.push(1)
stack.push(2)
print(stack.pop() as Any)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting the generic placeholder must be declared on the type itself (
struct Box<T>), not just on its methods. - Trying to use a generic type without specifying (or letting Swift infer) its concrete type parameter.
- Assuming a generic struct like
Stack<Int>andStack<String>are interchangeable; each concrete instantiation is a distinct type.
Chapter Summary
- A generic type declares its placeholder in angle brackets after the type name, like
struct Box<T>. - Once instantiated with a concrete type, like
Box<Int>, that placeholder is fixed for that instance. - Generic types let you write one reusable container or structure for many element types.
- Methods inside a generic type can use the placeholder type freely.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: