Subscript
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.
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 anInt
parameter (index
) and returns anInt
value.get
: The getter block should return the value corresponding to theindex
.set
: The setter block should set a new value at the specifiedindex
.
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: Intsubscript(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
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.