Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Define Generic Types
Written by Team Kodeco

In Swift, generic types allow you to write flexible and reusable code by abstracting away specific types. A generic type is defined by placing one or more placeholder types, called type parameters, within angle brackets (< >).

Here’s an example of how to define a generic type in Swift:

struct Stack<Element> {
  var items = [Element]()

  mutating func push(_ item: Element) {
    items.append(item)
  }

  mutating func pop() -> Element? {
    return items.popLast()
  }
}

var stackOfStrings = Stack<String>()
stackOfStrings.push("hello")
stackOfStrings.push("world")
if let item = stackOfStrings.pop() {
  print(item) // prints "world
}

var stackOfInts = Stack<Int>()
stackOfInts.push(1)
stackOfInts.push(2)
if let item = stackOfInts.pop() {
  print(item) // prints "2
}

In this example, the Stack struct is defined as a generic type, with a single type parameter Element. The type parameter is used to specify the type of elements that the stack holds. This allows the Stack struct to be used with any type, such as String or Int, as shown in the example above.

When creating a new instance of a generic type, you can specify the actual types to use for the type parameters by providing them within angle brackets after the type name. In the examples above, you used Stack<String> and Stack<Int> to create instances of the Stack struct that hold String and Int elements, respectively.

Use Multiple Type Parameters on Swift Generics

It’s possible to specify multiple type parameters by separating them with commas. For example:

struct Pair<T, U> {
  let first: T
  let second: U
}

Use Constraints on Swift Generics

You can specify constraints on the type parameters. For example, to restrict the type parameter to be a subclass of a certain class or to conform to a certain protocol:

protocol Flyable {
  func fly()
}

class Bird: Flyable {
  func fly() {
    print("I can fly")
  }
}

struct Flight<T: Flyable> {
  let flyingObject: T
}

let flight = Flight(flyingObject: Bird())
flight.flyingObject.fly() // prints "I can fly"
© 2024 Kodeco Inc.