Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Subscripts in Swift
Written by Team Kodeco

Subscripts in Swift are a shorthand way to access elements of a collection, list, or sequence. They allow you to access elements of a class or structure using square brackets [] instead of calling a method.

Here’s an example of how to define a subscript in a class:

class MyList {
  var items: [String]
  
  init(items: [String]) {
    self.items = items
  }
  
  subscript(index: Int) -> String {
    get {
      return items[index]
    }
    set {
      items[index] = newValue
    }
  }
}

This creates a new class called “MyList” with a subscript that allows you to access the elements of the “items” array by index.

You can use the subscript to access or set the elements of the array like this:

let myList = MyList(items: ["apple", "banana", "orange"])
print(myList[1]) // prints "banana"
myList[1] = "mango"
print(myList.items) // prints ["apple", "mango", "orange"]
© 2024 Kodeco Inc.