Horje
Swift - Subscripts

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



Reffered: https://www.geeksforgeeks.org


Swift

Related
Swift - Inheritance Swift - Inheritance
Swift Tutorial Swift Tutorial
Closures in Swift (With Examples) Closures in Swift (With Examples)
Calling Functions in Swift Calling Functions in Swift
Escaping and Non-Escaping Closures in Swift Escaping and Non-Escaping Closures in Swift

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14