Swift Chinese manual-subscripts

Source: Internet
Author: User
Affiliated scripts

Affiliated scriptsObjects such as class, structure, and enumeration 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, you can use an affiliated script to access elements in an array instance.someArray[index]To access the elements in the dictionary instance.someDictionary[key].

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 how to define an instance, use the custom scripts.subscriptKeyword, which explicitly declares the input parameter (one or more) and return type. 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 }}

newValueMust be of the same type as the returned type defined by the affiliated script. The same as the computing attribute is the set input parameter declaration.newValueYou can still use the defaultnewValueThis variable is used to access the new value.

Similar to read-only computing attributes, you can directly writegetThe code in the code block is written insubscriptMedium:

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

The following code demonstratesTimesTableThe usage of the read-only affiliated script in the struct, which is used to display the input integerNTimes.

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 exampleTimesTableThe struct creates an instance that represents three times the index value. Value3As structConstructorInitialize instance members with input parametersmultiplier.

You can get the result through the affiliated script, suchthreeTimesTable[6]. This sentence is accessedthreeTimesTableAnd returns18Or6Of3Times.

Note:

TimesTableThe example is based on a fixed mathematical formula. It is not suitablethreeTimesTable[someIndex]Assign values, which 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

In the preceding example, a name is definednumberOfLegsAnd initialize a dictionary instance that contains three pairs of key values.numberOfLegsThe dictionary storage value type is inferredDictionary<String, Int>. After the dictionary instance is created, use the affiliated script to convert the integer value.2The index assigned to the dictionary instance isbird.

Note:

In the implementation of the dictionary affiliated script in swiftgetPartial return values areInt?In the preceding examplenumberOfLegsThe dictionary returnsInt?Or "Optional int", not every dictionary index can get an integer value. The result returned for access to an index without any value isnilTo delete the value of an index from the dictionary instance, you only need to assign the valuenilYou can.

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 will be automatically matched for running. This isAttach script overload.

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 definesMatrixStruct to presentDoubleType two-dimensional matrix.MatrixThe affiliated script of the 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 of range")            return grid[(row * columns) + column]        }        set {            assert(indexIsValidForRow(row, column: column), "Index out of range")            grid[(row * columns) + columns] = newValue        }    }}

MatrixProvides a constructor for two input parameters. The input parameters arerowsAndcolumns, Create a sufficient capacityrows * columnsNumberDoubleType array. 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.

You can pass in the appropriaterowAndcolumnTo construct a newMatrixInstance:

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

In the above example, a new two-row and two-columnMatrixInstance. Reading order from top left to bottom rightMatrixArray instances in the instancegridIs the flat storage of matrix 2D arrays:

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

Assign a value torowAndcolumnAffiliated scriptsmatrixThe instance expression can be used to assign values. The input parameters of the affiliated script are separated by commas (,).

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

The preceding two statements are respectivelyLet MatrixThe upper-right value is 1.5, and the sit-down value is 3.2:

[0.0, 1.5, 3.2, 0.0]

MatrixAffiliated scriptsgetterAndsetterThe attached script input parameters are also called.rowAndcolumnWhether it is valid. To facilitate assertions,MatrixContainsindexIsValidMember method, used to confirm the input parameterrowOrcolumnWhether the value will cause array out of bounds:

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
Swift QQ Group

Swift mutual communication QQ group: 74512850, so that fans can make progress together! The full Chinese PDF file is available in the group!

Click the link to join the group [swift development mutual assistance]: http://jq.qq.com /? _ WV = 1027 & K = nwgksv

Chinese manual navigation

Blog: Click to enter the navigation bar

GitHub: Click to enter the navigation bar

 
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.