← 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.

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
struct Box<T> {
    var value: T
}
let intBox = Box(value: 42)
let stringBox = Box(value: "hello")
print(intBox.value)
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
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)
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.