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:
Syntax
struct TypeName<T> {
var value: T
var items: [T] = []
mutating func method(_ item: T) {
items.append(item)
}
}
let instance = TypeName<Int>(value: 1)
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
// Define a struct `Box`
struct Box<T> {
var value: T
}
// Declare a constant `intBox`, set to `Box(value: 42)`
let intBox = Box(value: 42)
// Declare a constant `stringBox`, set to `Box(value: "hello")`
let stringBox = Box(value: "hello")
// Print `intBox.value` to the console
print(intBox.value)
// Print `stringBox.value` to the console
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
// Define a struct `Stack`
struct Stack<Element> {
private var items: [Element] = []
mutating func push(_ item: Element) {
// Append `item` to `items`
items.append(item)
}
mutating func pop() -> Element? {
// Return `items.popLast()` from this function
return items.popLast()
}
}
// Declare a mutable variable `stack`, initialized to `Stack<Int>()`
var stack = Stack<Int>()
stack.push(1)
stack.push(2)
// Print `stack.pop() as Any` to the console
print(stack.pop() as Any)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: