Swift - Subscripts



Subscript is a special feature provided by Swift to access the element of a collection, sequence and list. It is the most convenient way to get or set values in the collection. We can also get or set values according to their index using subscripts. Even classes, structure and enumeration can define subscripts.

A single type can have multiple subscripts. We can use the appropriate subscript to overload according to the type of index value passed to the subscript. We can define a subscript that can take single as well as multiple parameters according to our requirements.

Subscript Declaration

We can define subscript using the subscript keyword and can take one or more input parameters and return type. It can be read-write or read-only. It allows us to perform queries on the instance by writing one or more values in square brackets followed by the instance name.

Syntax

Following is the syntax of the subscript −

subscript(index: Int) -> Int {
   get {
      // Retrieve the value at the specified index
   }
   set(newValue) {
      // Set the value at the specified index
   }
}

Following is the syntax of read-only subscript −

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

Example

Swift program to retrieve values using subscript syntax.

// Defining structure
struct subexample {
   let decrementer: Int
    
   // Declaring subscript
   subscript(index: Int) -> Int {
      return decrementer / index
   }
}

// Creating instance of the structure
let division = subexample(decrementer: 100)

// Retrieving values using subscript syntax
print("The number is divisible by \(division[9]) times")
print("The number is divisible by \(division[2]) times")
print("The number is divisible by \(division[3]) times")
print("The number is divisible by \(division[5]) times")
print("The number is divisible by \(division[7]) times")

Output

It will produce the following output −

The number is divisible by 11 times
The number is divisible by 50 times
The number is divisible by 33 times
The number is divisible by 20 times
The number is divisible by 14 times

Example

Swift program to access values using subscript syntax.

// Defining class
class daysofaweek {

   private var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
    
   // Declaring subscript    
   subscript(index: Int) -> String {
    
      // Retrieve the value at the specified index
      get {
         return days[index]
      }
        
      // Set the value at the specified index 
      set(newValue) {
         self.days[index] = newValue
      }
   }
}

// Creating instance of class
var p = daysofaweek()

// Accessing elements using subscript
print(p[0])
print(p[1])
print(p[2])
print(p[3])

Output

It will produce the following output −

Sunday
Monday
Tuesday
Wednesday

Options in Subscript

Subscripts can take single or multiple input parameters of any data type and it can also return a value of any data type. These parameters can have default values. Subscripts can use variadic parameters but they cannot use in-out parameters.

Defining multiple subscripts is termed as 'subscript overloading' where a class or structure can provide multiple subscript definitions as required. These multiple subscripts are inferred based on the types of values that are declared within the subscript braces.

Example

Swift program to access values using subscript syntax.

// Defining structure
struct Matrix {

   let rows: Int, columns: Int
   var print: [Double]

   // Initializer to create a matrix 
   init(rows: Int, columns: Int) {
      self.rows = rows
      self.columns = columns
        
      // Initializing the matrix with an array 
      print = Array(repeating: 0.0, count: rows * columns)
   }

   // Subscript for accessing and modifying elements in the matrix
   subscript(row: Int, column: Int) -> Double {
      get {
         return print[(row * columns) + column]
      }
      set {
         print[(row * columns) + column] = newValue
      }
   }
}

// Creating an instance 
var mat = Matrix(rows: 3, columns: 3)

// Modifying elements in the matrix using subscript notation
mat[0, 0] = 1.0
mat[0, 1] = 2.0
mat[1, 0] = 3.0
mat[1, 1] = 5.0

// Accessing and printing elements from the matrix using subscript notation
print("\(mat[0, 0])") 
print("\(mat[0, 1])") 
print("\(mat[1, 0])") 
print("\(mat[1, 1])") 

Output

It will produce the following output −

1.0
2.0
3.0
5.0
Advertisements