Accessing elements of a collection, subscripts can be used in sequences and lists, structures and enumerations in the class. These subscripts are used to store and use indexes to retrieve values. Array elements can be used, such as: someArray[index], and access to Dictionary instances and subsequent member elements can also be used, such as: someDicitonary[key].
For a single type, the subscript range can range from a single to multiple declarations. We can pass the type of the index value with appropriate subscript overload. Subscripts can also declare ranges from single to multi-dimensional based on input data type.
Subscript declaration syntax and usage
Let's review the computed properties. Subscripts also follow the same syntax for computing properties. The instance subscript for the query type is enclosed in square brackets, followed by the instance name. The subscript syntax follows the same syntax as the "instance method" and "computed attributes". The "subscript" keyword is used to define the tag, and the user can specify one or more parameters with a return type. Subscripts can have read-write or read-only attributes and instance storage and retrieval using the "getter" and "setter" attributes as computed attributes.
grammar
subscript(index:Int)->Int{get{// used for subscript value declarations}set(newValue){// definitions are written here}}
Example 1
struct subexample {let decrementer:Int
subscript(index:Int)->Int{return decrementer / index
}}let division = subexample(decrementer:100)
println("The number is divisible by \(division[9]) times")
println("The number is divisible by \(division[2]) times")
println("The number is divisible by \(division[3]) times")
println("The number is divisible by \(division[5]) times")
println("The number is divisible by \(division[7]) times")
When we run the above program using playground, we get the following results
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 2
class daysofaweek {privatevar days =["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","saturday"]
subscript(index:Int)->String{get{return days[index]}set(newValue){[index]= newValue
}}}var p = daysofaweek()
println(p[0])
println(p[1])
println(p[2])
println(p[3])
When we run the above program using playground, we get the following results
Sunday Monday Tuesday Wednesday
Subscript options
The subscript uses single to multiple input parameters, which also belong to any data type. You can also use variable parameters. The subscript cannot provide default parameter values, or use any in-out parameter.
Defining multiple marks is called "subscript overloading". Multiple subscript definitions can be provided in a class or structure as needed. These multiple marks are inferred based on the type of value declared in subscript brackets.
structMatrix{let rows:Int, columns:Intvarprint:[Double]
init(rows:Int, columns:Int){ = rows
= columns
print=Array(count: rows * columns, repeatedValue:0.0)}
subscript(row:Int, column:Int)->Double{get{returnprint[(row * columns)+ column]}set{print[(row * columns)+ column]= newValue
}}}var mat =Matrix(rows:3, columns:3)
mat[0,0]=1.0
mat[0,1]=2.0
mat[1,0]=3.0
mat[1,1]=5.0
println("\(mat[0,0])")
println("\(mat[0,1])")
println("\(mat[1,0])")
println("\(mat[1,1])")
When we run the above program using playground, we get the following results
1.0 2.0 3.0 5.0
Swift subscript supports single-parameter to multi-parameter declaration of corresponding data types. The "matrix" structure declared by the program is a 2*2-dimensional array matrix to store the "Double" data type. The matrix parameters are entered into integer data types to declare rows and columns.
A new matrix instance is initialized by making the number of rows and columns, as shown below.
var mat = Matrix(rows: 3, columns: 3)
Matrix values can be defined as follows by passing row and column values to subscripts, separated by commas.
mat[0,0] = 1.0
mat[0,1] = 2.0
mat[1,0] = 3.0
mat[1,1] = 5.0
Definition of subscript method
The definition syntax of the subscript method is similar to that of the instance method and the computed attributes.
The subscript method uses the subscript keyword to indicate that it is a subscript method. Like the example method, one or more input parameters can be specified in the subscript method definition, with a return type. Unlike the example method, the subscript method can be read-write or read-only. Like the definition of computed properties, the subscript method conveys the behavior of the subscript method by using getters and setters. If both getter and setter are specified in the definition of the subscript method, a readable and writeable subscript method is defined. If the definition of the subscript method does not contain a setter, a read-only subscript method is defined, and the keyword get representing the getter method can also be omitted. The complete syntax of the subscript method definition is as follows:
subscript(index:Int) ->Int {
get {
// return an appropriate subscript value here
}
set(newValue) {
// perform a suitable setting action here
}
}
This example defines a readable and writeable subscript method. NewValue can be specified or not. When not specified, the default parameter name newValue is used.
The following example shows the definition and use of a read-only subscript method. Since the read-only subscript method only specifies one getter and the meaning is clear, the get keyword can be omitted.
struct TimesTable {
let multiplier:Int
subscript(index:Int) ->Int {
return multiplier *index
}
}
let threeTimesTable =TimesTable(multiplier:3)
println("six times three is\(threeTimesTable[6])")
// prints "six times three is 18”
Use of subscripting methods
You can define and implement multiple subscript methods for a type, and the compiler infers and selects the appropriate subscript method based on the type of index parameters you pass to the subscript method.
Similar to methods, the subscript method can contain any number of input parameters, and the types of these input parameters can be of any type, and the subscript method can also return any type. The subscript method can also use variable parameters, but cannot use in-out parameters or pass the default parameter value.
For example, you can define a subscript method that represents multiple latitudes with multiple input parameters. The following example shows how to define a subscript method with two integer types for a matrix structure and how to use it. The defined subscript method is used to index elements of two latitudes defined in the matrix.
struct Matrix {
let rows:Int,columns:Int
var grid:Double[]
init(rows:Int,columns:Int) {
=rows
=columns
grid =Array(count:rows *columns,repeatedValue:0.0)
}
subscript(row:Int,column:Int) ->Double {
get {
return grid[(row *columns) +column]
}
set {
grid[(row *columns) +column] =newValue
}
}
}
var matrix =Matrix(rows:2,columns:2)
matrix[0,1] =1.5
matrix[1,0] =3.2