Explain the use of the subscript in Swift programming

  • 2020-05-14 05:01:10
  • OfStack

To access the element members of a collection, subscripts can be used for sequences and lists, structures, and enums in a class. These subscripts are used to store and use indexes to retrieve values. Array elements can be used as someArray[index], or access to an Dictionary instance and its subsequent member elements can be used as someDicitonary[key].

For single 1 types, subscripts can range from single 1 to multiple declarations. We can use the appropriate subscript overload to pass the type of the subscript index value. Subscripts can also be declared from single 1 dimension to multiple dimensions based on the input data type.

Subscripts declare grammar and usage
Let's review 1 for calculating properties. Subscripts also follow the same syntax for calculating attributes. The instance subscript for the query type is enclosed in square brackets, followed by the instance name. The subscript syntax follows the structure as the same syntax for "instance methods" and "calculated properties." 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 properties and instance storage and retrieval using "getter" and "setter" properties as calculated properties.

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){self.days[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

The subscript options
The subscripts take the form of single 1 to multiple input parameters, which are also of arbitrary data types. You can also use variables, variable parameters of the parameters. Subscripts cannot provide default parameter values, or use any in-out parameters.

Defining multiple subscripts is called 'subscript overloading' in a class or structure that can provide multiple subscript definitions as needed. These multiple indices are inferred based on the type of value declared in the subscript parenthesis.


structMatrix{let rows:Int, columns:Intvarprint:[Double]
    init(rows:Int, columns:Int){self.rows = rows
        self.columns = 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

The Swift subscript supports single-parameter to multi-parameter declarations of corresponding data types. The "matrix" structure declared by the program is a 2-by-2-dimensional array matrix to store the "Double" data type. Matrix parameters are used by the input integer data type to declare rows and columns.

A new instance of the matrix is created by initializing the number of rows and columns, as shown below.


 var mat = Matrix(rows: 3, columns: 3)

Matrix values can be defined by passing row and column values to subscripts, separated by commas, as shown below.


mat[0,0] = 1.0 
mat[0,1] = 2.0
mat[1,0] = 3.0
mat[1,1] = 5.0

The definition of subscript methods
The syntax for defining subscript methods is similar to that for instance methods and computed properties.
The subscript method USES the subscript keyword to indicate that it is a subscript method. As with instance method 1, subscript method definitions can specify one or more input parameters with one return type. Unlike instance methods, subscript methods can be read-write or read-only. Like the definition of the calculated attribute 1, the subscript method communicates the behavior of the subscript method by using getter and setter. If both getter and setter are specified in the definition of the subscript method, a read-write subscript method is defined. If the definition of the subscript method does not include setter, a read-only subscript method is defined, and the keyword get representing the getter method may also be omitted. The full 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
    }
}
     The example is defined 1 Two read-write subscript methods, newValue You may or may not specify, and you may use the default parameter name when not specified newValue .
     Here's an example 1 The definition and use of three read-only subscript methods. Because the read-only subscript method is specified only 1 a getter ", so it can be omitted get The keyword.
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 "

The use of subscript methods
You can define and implement multiple subscript methods for one type, and the compiler extrapolates and selects the appropriate subscript method based on the type of the index parameter you pass to the subscript method.
Like methods, subscript methods can contain any number of input parameters of any type, and subscript methods can return any type. Subscript methods can also use mutable parameters, but they cannot use the in-out parameter and they cannot use the default parameter value.
If it is possible to define a subscript method representing 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 the subscript method defined to index the two-latitude elements defined in the matrix.

struct Matrix {
   let rows:Int,columns:Int
   var grid:Double[]
   init(rows:Int,columns:Int) {
       self.rows =rows
       self.columns =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


Related articles: