Open In App

Swift – Subscripts

Last Updated : 12 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Subscripts are used to access the element members of a collection, sequence, or list in Classes, Structures, and Enumerations. These subscripts are used to store and retrieve the values with the aid of an index. SomeDicitonary[key] is used to access dictionary instances’ later member elements, and someArray[index] is used to access array elements. 

For a single type, subscripts may have one or more declarations. Using the right subscript, we can overload the type of index value that is sent to the subscript. Depending on what the user wants for their declarations of the input data type, subscripts can also be one or more dimensions. 

How to use:

Subscript syntax is the same as computed property syntax. When querying type instances, subscripts come after the instance name in square brackets. The “instance method” and “computed property” syntaxes share the same syntax structure as the “subscript” syntax. Subscripts are defined by the keyword “subscript,” and users can specify one or more parameters as well as the return types for those parameters. The same “getter” and “setter” properties that are computed for subscripts, which can have read-write or read-only properties, are used to store and retrieve instances.

subscript(index: Int) −> Int {
   get {
      // subscript value declared
   }
   set(newValue) {
      // Write defination 
   }
}

The syntax of subscripts is the same as that of computed properties. When querying type instances, subscripts come after the instance name in square brackets.

Swift




import Swift
class monthsinyear { 
   private var months = ["January ", "February ", "March", "April"
      "May", "June", "July" , "August", "September", "October" , "November" , "December"
   subscript(index: Int) -> String
      get
         return months[index] 
      
      set(newValue) { 
         self.months[index] = newValue 
      
   
var p = monthsinyear() 
print(p[0])    // Here, we are printing names of months in indivually
print(p[1]) 
print(p[2]) 
print(p[3]) 
print(p[4]) 
print(p[5]) 
print(p[6])
print(p[7])
print(p[8])
print(p[9])
print(p[10])
print(p[11])


OUTPUT

January
February 
March
April  
May
June 
July
August
September
October
November
December

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads