iOS development Language Swift entry---subscript script

Source: Internet
Author: User

iOS development language Swift Getting started serial-subscript script

Subscript scripts can be defined in the classes (class), struct (structure), and enumeration (enumeration) targets, which can be thought of as shortcuts to accessing objects, collections, or sequences, without the need to invoke specific assignments and access methods for the instance. For example, using the subscript script to access elements in an array instance can be written Somearray[index], and the elements in the Access Dictionary (Dictionary) instance can be written Somedictionary[key].
Multiple subscript scripts can be defined for the same target, overloaded by different index value types, and the number of indexed values can be multiple.
Translator: Here the attached script overloads are not shown in the original text in this section
  

Subscript script Syntax

The subscript script allows you to access and assign values to an instance by passing in one or more index values in the brackets behind the instance. Syntax is similar to the blending of instance methods and computed properties. Similar to defining an instance method, the subscript script is defined using the SUBSCRIPT keyword to explicitly declare the in parameter (one or more) and the return type. Unlike instance methods, subscript scripts can be set to read-write or read-only. This approach is somewhat like the getter and setter of computed properties:

subscript(index: Int) -> Int {    get {      // 返回与入参匹配的Int类型的值    }    set(newValue) {      // 执行赋值操作    }}

The type of newvalue must be the same as the return type defined by the subscript script.  The same as the computed attribute is the parameter declaration of the set newvalue even if not written, the default newvalue variable can still be used to access the newly assigned value in the set code block. As with read-only computed properties, you can write the code that should be written in the get code block directly in subscript:

subscript(index: Int) -> Int {    // 返回与入参匹配的Int类型的值}

The following code demonstrates the use of a read-only subscript script in a timestable struct that shows n times the number of incoming integers.

struct TimesTable {    letmultiplier: Int    subscript(index: Int) -> Int {      return multiplier * index    }}let threeTimesTable = TimesTable(multiplier3)println("3的6倍是\(threeTimesTable[6])")//"3的6倍是18"

In the example above, a timestable structure was created to represent an instance of three times times the index value. A value of 3 initializes the instance member multiplier as a struct constructor.
You can get results using subscript scripts, such as Threetimestable[6]. This statement accesses the sixth element of the threetimestable and returns 3 times times 6, or 18.
Attention:
The timestable example is based on a fixed mathematical formula. It is not suitable for open Write permissions to assign operations to Threetimestable[someindex], which is why the satellite script is only defined as read-only.

Subscript Script Usage

  
The subscript script also has different meanings depending on the usage scenario. Typically subscript scripts are shortcuts that are used to access elements in a collection (collection), list, or sequence (sequence). You can freely implement subscript scripts in your own particular class or struct to provide the appropriate functionality.
For example, Swift's Dictionary (Dictionary) implements access to the values stored in its instance through the subscript script. Use the same type of value as the dictionary index in the subscript script, and assign a value of the dictionary value type to the subscript script to set the value for the dictionary:

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

The example above defines a variable named Numberoflegs and initializes a dictionary instance with three pairs of key values with a dictionary literal. The dictionary storage value type of Numberoflegs is inferred as dictionary. After the dictionary instance is created, the integer value 2 is assigned to the location of the dictionary instance's index as bird, using the subscript script.
For more information on the dictionary (Dictionary) subscript script, refer to reading and modifying dictionaries
Attention:
In the subordinate script implementation of the dictionary, the return value in the get part is int? , the Numberoflegs dictionary in the example above is returned by a satellite script an int? or "optional int", not the index of each dictionary can get an integer value, for the index without the value of the access to return the result is nil, also want to remove from the dictionary instance the value under an index is only required to assign the index to nil.

Subscript Script Options

 
The subscript script allows any number of index parameters, and there is no limit to the type of entry. The return value of the subscript script can also be of any type. Subscript scripts can use variable arguments and variable parameters, but using the write read-out (in-out) parameter or setting a default value for a parameter is not allowed.
A class or struct can provide multiple subscript script implementations based on its own needs, which are differentiated by the type of the incoming parameter when the subscript script is defined, and the subscript script automatically matches the appropriate subscript script implementation to run, which is the overload of the subscript script.
Subscript script entry is the most common case, but you can define multiple subscript script entry parameters as long as there is a suitable scenario. The following example defines a matrix struct that renders a two-dimensional matrix of type double. The subscript script for a Matrix struct requires two integer parameters:

struct Matrix { LetRowsInt, Columns:Intvar 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 of range") return grid[(Row * columns) + column]}Set{Assert (Indexisvalidforrow (row, Column:column),"Index out of range") grid[(Row * columns) + column] = newvalue}}

The Matrix provides a two-entry constructor, where the entry is rows and columns, creating an array of double types sufficient to hold the number of rows * columns. In order to store, the size of the array and the initial value of each element in the array, 0.0, are passed into the construction method of the arrays to create a new array of the correct size. For the construction and destruction of arrays, refer to creating and constructing an array.
You can construct a new matrix instance by passing in the appropriate number of row and columns:

var= Matrix(rows22)

In the example above, a new matrix instance of two rows of two columns was created. An array instance of the matrix instance in the reading order from top left to bottom right is a flattened storage of a two-dimensional array of matrices:

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

Assigning a value to a matrix instance expression with a row and column subscript script completes the assignment, and the subscript script entry uses a comma-delimited

matrix[011.5matrix[103.2

The above two statements give the matrix a value of 1.5 for the top right, and a value of 3.2 for sitting down:

[0.01.53.20.0]

The Matrix subscript script's getter and setter both invoke the row and column of the subscript script into the valid judgment. To facilitate assertions, the Matrix contains a member method named Indexisvalid, which confirms that the row or column value of the entry will cause the array to be out of bounds:

func indexIsValidForRow(row: Int, column: Int) -> Bool {    return00 && column < columns}

The assertion is triggered when the subscript script is out of bounds:

let someValue = matrix[22]// 断言将会触发,因为 [2, 2] 已经超过了matrix的最大长度

iOS development Language Swift entry---subscript script

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.