← Back to Swift Course | Chapter 12: Generics & Advanced Types | Lesson 2 of 7

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.
Syntax
swift
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

markup
// 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)

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

markup
// 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)
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
  1. Forgetting the generic placeholder must be declared on the type itself (struct Box<T>), not just on its methods.
  2. Trying to use a generic type without specifying (or letting Swift infer) its concrete type parameter.
  3. Assuming a generic struct like Stack<Int> and Stack<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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.