Swift Subscript

arisdelaCruz1413618857's avatar
Published Sep 12, 2024
Contribute to Docs

Subscript in Swift is a shortcut for accessing elements of a collection, list, or sequence. It is syntactic sugar that allows the use of the subscript syntax [] to access elements. Subscripts can also be defined in custom types, with syntax similar to computed properties. Multiple subscripts can be defined with different input parameters and return types.

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours

Syntax

The syntax for defining a subscript in Swift is as follows:

subscript(index: Int) -> Int {
  get {
    // Return an appropriate subscript value here
  }

  set(newValue) {
    // Perform a suitable setting action here
  }
}
  • subscript(index: Int) -> Int: This defines a subscript that takes an Int parameter (index) and returns an Int value.
  • get: The getter block should return the value corresponding to the index.
  • set: The setter block should set a new value at the specified index.

Example

This example creates a TimesTable structure with a subscript that returns the product of the multiplier and the index. The subscript is accessed using the [] syntax to compute the result:

struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("Six times three is \(threeTimesTable[6])")

The above code produces the following output:

Six times three is 18

All contributors

Contribute to Docs

Learn Swift on Codecademy

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours