Swift programming language-subscripts)

Source: Internet
Author: User

The affiliated scripts can be defined in objects such as class, structure, and enumeration. They can be considered as shortcuts to access objects, sets, or sequences, you do not need to call the instance's specific assignment and access methods. For example, to access elements in an array (array) instance using a ancillary script, you can write somearray [Index] in this way, and to access elements in a dictionary instance, you can write somedictionary [Key] in this way.

 

For the same target, you can define multiple ancillary scripts and perform heavy loads based on different index value types, and the number of index values can be multiple.

 

The attached script overload is not demonstrated in this section.

 

Ancillary script syntax

The affiliated script allows you to access and assign values to an instance by inputting one or more index values in square brackets after the instance. The syntax is similar to the mixing of instance methods and computing attributes. Similar to the instance definition method, the custom scripts use the subscript keyword to explicitly declare input parameters (one or more) and return types. Different from the instance method, the affiliated scripts can be set to read/write or read-only. This method is a bit like getter and setter of the compute attribute:

 

Subscript (Index: INT)-> int {get {// return the int type value that matches the input parameter} set (newvalue) {// perform the value assignment operation }}


The newvalue type must be the same as the return type defined by the affiliated script. The same as the computing attribute is that even if newvalue is not written, the default newvalue variable can still be used in the Set code block to access the newly assigned value.

 

Like read-only computing attributes, you can directly write the code originally written in the get code block to Subscript:

 

Subscript (Index: INT)-> int {// return the int type value that matches the input parameter}


The following code demonstrates the usage of a read-only ancillary script in the timestable struct, which is used to display n times of the input integer.

 

Struct timestable {let multiplier: int subscript (Index: INT)-> int {return multiplier * index} Let threetimestable = timestable (multiplier: 3) println ("6 times of 3 is \ (threetimestable [6])") // output "6 times of 3 is 18"


In the preceding example, an instance is created using the timestable struct to indicate three times the index value. Value 3 is used as the struct constructor input parameter to initialize the instance Member multiplier.

 

You can obtain the result through the affiliated script, such as threetimestable [6]. This statement accesses the sixth element of threetimestable and returns 3 times of 18 or 6.

 

Note:

 

The timestable example is based on a fixed mathematical formula. It is not suitable for assigning values to threetimestable [someindex] with open write permissions. This is why the affiliated scripts are only defined as read-only.

 

Affiliated script usage

Scripts attached to different use cases have different meanings. A companion script is a shortcut used to access elements in a collection, list, or sequence. You can freely implement the affiliated scripts in your own specific classes or struct to provide the appropriate functions.

 

For example, the swift dictionary allows users to access the values stored in their instances through the affiliated scripts. Use a value of the same type as the dictionary index in the affiliated script, and assign a value of the dictionary value type to this affiliated script to set a value for the dictionary:

 

var numberOfLegs = ["spider": 8,"ant": 6, "cat": 4]numberOfLegs["bird"] = 2


The preceding example defines a variable named numberoflegs and initializes a dictionary instance containing three pairs of key values using a dictionary literal. The dictionary storage value type of numberoflegs is inferred to be dictionary <string, int>. After the dictionary instance is created, the integer value 2 is assigned to the index of the dictionary instance to the position of bird by means of the affiliated script.

 

For more information about dictionary affiliated scripts, see read and modify dictionaries.

 

Note:

 

In the implementation of the dictionary affiliated script in swift, the return value in the get part is int ?, In the above example, the numberoflegs dictionary returns an int through the following? Or an "Optional int" means that not every dictionary index can obtain an integer value. The returned result for access to an index without any value is nil; to delete the value of an index from a dictionary instance, you only need to assign the value to nil.

 

Additional script options

The affiliated script allows any number of input parameter indexes, and each input parameter type is not limited. The returned value of the affiliated script can also be of any type. The affiliated scripts can use variable parameters and variable parameters, but they are not allowed to use the in-out parameter or set the default value for the parameter.

 

A class or struct can be implemented by providing multiple affiliated scripts according to its own needs. when defining the affiliated scripts, It is differentiated by the input parameter types, when the affiliated script is used, the appropriate affiliated script is automatically matched for running, which is the heavy load of the affiliated script.

 

One ancillary script input parameter is the most common condition, but multiple ancillary script input parameters can be defined as long as there is an appropriate scenario. The following example defines a matrix struct and presents a two-dimensional matrix of the double type. The affiliated script of the matrix struct requires two integer parameters:

 

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)    }   func indexIsValidForRow(row: Int, column: Int) -> Bool {       return row >= 0 && row < rows && column >= 0&& column < columns    }   subscript(row: Int, column: Int) -> Double {       get {           assert(indexIsValidForRow(row, column: column), "Index out ofrange")           return grid[(row * columns) + column]       }       set {           assert(indexIsValidForRow(row, column: column), "Index out ofrange")           grid[(row * columns) + columns] = newValue       }    }}


Matrix provides a constructor for two input parameters, rows and columns, respectively, and creates an array of the double type that is sufficient to accommodate the number of rows * columns. For storage, the size of the array and the initial value of each element in the array are 0.0, And the Array Construction Method is passed in to create a new array with the correct size. For the Array Construction Method and destructor, see Create and construct an array.

 

You can input the appropriate number of rows and columns to construct a new matrix instance:

 

var matrix = Matrix(rows: 2, columns: 2)


In the preceding example, a new matrix instance with two rows and two columns is created. The array instance grid in the matrix instance in the reading sequence from top left to bottom right is a flat storage of two-dimensional arrays of the matrix:

 

// grid = [0.0, 0.0, 0.0, 0.0]        col0     col1row0  [0.0,     0.0,row1   0.0,     0.0]


Assign a value to a matrix instance expression with the row and column scripts to complete the assignment. The input parameters of the affiliated scripts are separated by commas.

 

matrix[0, 1] = 1.5matrix[1, 0] = 3.2


The preceding two statements respectively set the upper right of matrix to 1.5 and the lower right to 3.2:

 

[0.0, 1.5, 3.2,0.0]


In the getter and setter scripts of the matrix affiliated scripts, the row and column values of the input parameters of the affiliated scripts are also called to determine whether the row and column values are valid. To facilitate assertion, matrix contains a member method named indexisvalid to confirm whether the row or column value of the input parameter will cause the array to cross-border:

 

func indexIsValidForRow(row: Int, column:Int) -> Bool {   return row >= 0 && row < rows && column >= 0&& column < columns}


Assertion is triggered when the ancillary script crosses the border:

 

Let somevalue = matrix [2, 2] // The asserted will be triggered because [2, 2] has exceeded the maximum length of Matrix


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.