Swift Subscripts
Subscripts can be defined in classes, structures, and enumerations. They can be considered as shortcuts for accessing objects, collections, or sequences, eliminating the need to call specific assignment and access methods for instances.\n\nFor example, accessing an element in an Array instance using a subscript can be written as someArray, and accessing an element in a Dictionary instance can be written as someDictionary.\n\nMultiple subscripts can be defined for the same target, overloaded by different index value types, and the number of index values can be multiple.\n\n* * *\n\n## Subscript Syntax and Usage\n\n### Syntax\n\nSubscripts allow you to access and assign values to an instance by passing one or more index values in square brackets after the instance.\n\nThe syntax is a mix of instance methods and computed properties.\n\nSimilar to defining instance methods, defining a subscript uses the subscript keyword, explicitly declaring input parameters (one or more) and the return type.\n\nUnlike instance methods, subscripts can be set to read-write or read-only. This approach is somewhat like the getter and setter of computed properties:\n\nsubscript(index: Int) -> Int { get { // Declaration for subscript values } set(newValue) { // Execute assignment operation }}\n### Example 1\n\nimport Cocoastruct subexample { let decrementer: Int subscript(index: Int) -> Int { return decrementer / index }}let division = subexample(decrementer: 100)print("100 Divided by 9 equals \\(division)")print("100 Divided by 2 equals \\(division)")print("100 Divided by 3 equals \\(division)")print("100 Divided by 5 equals \\(division)")print("100 Divided by 7 equals \\(division)")\nThe output of the above program execution is:\n\n100 Divided by 9 equals 11100 Divided by 2 equals 50100 Divided by 3 equals 33100 Divided by 5 equals 20100 Divided by 7 equals 14\nIn the above example, an instance of a division operation is created through the subexample structure. The value 100 is passed as a parameter to the structure's initializer to initialize the instance member decrementer.\n\nYou can get the result through a subscript, for example, division is 100 divided by 2.\n\n### Example 2\n\nimport Cocoaclass daysofaweek { private var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "saturday"] subscript(index: Int) -> String { get { return days // Declare the value of subscript } set(newValue) { self.days = newValue // Execute assignment operation } }}var p = daysofaweek()print(p)print(p)print(p)print(p)\nThe output of the above program execution is:\n\nSundayMondayTuesdayWednesday\n### Usage\n\nDepending on the usage scenario, subscripts have different meanings.\n\nTypically, subscripts are used as shortcuts to access elements in a collection, list, or sequence.\n\nYou are free to implement subscripts in your specific classes or structures to provide appropriate functionality.\n\nFor example, Swift's Dictionary implements access to the values stored in its instances via subscripts. In a subscript, you use a value of the same type as the dictionary's key, and assign a value of the dictionary's value type to the subscript to set a value for the dictionary:\n\nimport Cocoavar numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] numberOfLegs = 2print(numberOfLegs)\nThe output of the above program execution is:\n\n["ant": 6, "bird": 2, "cat": 4, "spider": 8]\nThe above example defines a variable named numberOfLegs and initializes a dictionary instance containing three key-value pairs using a dictionary literal. The stored value type of the numberOfLegs dictionary is inferred as Dictionary. After the dictionary instance is created, the integer value 2 is assigned to the index "bird" in the dictionary instance via a subscript.\n\n* * *\n\n## Subscript Options\n\nSubscripts allow any number of input index parameters, and there is no restriction on the type of each input parameter.\n\nThe return value of a subscript can also be of any type.\n\nSubscripts can use variable parameters and variadic parameters.\n\nA class or structure can provide multiple subscript implementations as needed. When defining subscripts, they are distinguished by the type of input parameters. When a subscript is used, the appropriate subscript implementation is automatically matched and executed. This is **subscript overloading**.\n\nimport Cocoastruct Matrix { let rows: Int, columns: Int var print: init(rows: Int, columns: Int) { self.rows = rows self.columns = columns print = Array(repeating: 0.0, count: rows * columns) } subscript(row: Int, column: Int) -> Double { get { return print[(row * columns) + column] } set { print[(row * columns) + column] = newValue } }}// Created a new 3 row 3 column Matrix instance var mat = Matrix(rows: 3, columns: 3)// Set value via subscript mat[0,0] = 1.0 mat[0,1] = 2.0 mat[1,0] = 3.0 mat[1,1] = 5.0// Get value via subscript print("\\(mat[0,0])")print("\\(mat[0,1])")print("\\(mat[1,0])")print("\\(mat[1,1])")\nThe output of the above program execution is:\n\n1.02.03.05.0\nThe Matrix structure provides an initializer with two input parameters, rows and columns, which creates an array of Double type large enough to hold rows * columns elements. For storage, the size of the array and the initial value of each element are set to 0.0.\n\nYou can construct a new Matrix instance by passing in the appropriate number of rows and columns.
YouTip