Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Generic Subscripts
Written by Team Kodeco

In Swift, you can use generic subscripts to define a subscript that can be used with any type of collection. A generic subscript is defined by using the subscript keyword, followed by a generic parameter list and a return type.

Here’s an example of how to use generic subscripts in Swift:

struct Stack<Element> {
  var items = [Element]()
  mutating func push(_ item: Element) {
    items.append(item)
  }

  mutating func pop() -> Element? {
    guard !items.isEmpty else {
      return nil
    }
    return items.removeLast()
  }

  subscript<Indices: Sequence>(
    indices: Indices
  ) -> [Element]
  where Indices.Iterator.Element == Int {
    var result = [Element]()
    for index in indices {
      guard index < items.count else {
        continue
      }
      result.append(items[index])
    }
    return result
  }
}

var stack = Stack<String>()
stack.push("uno")
stack.push("dos")
stack.push("tres")

print(stack[[0,2]]) // Prints ["uno", "tres"]

In this example, the Stack struct is defined as a generic struct, with a single generic parameter Element. The struct contains an array items of type [Element] and two mutating functions push(_:) and pop().

The generic subscript takes a single parameter indices of any type that conforms to the Sequence protocol and its Iterator.Element must be of type Int. The subscript then returns an array of elements that exist at the indices specified in the indices parameter and any index that is out of bound is ignored.

© 2024 Kodeco Inc.