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.subscript
Keyword, 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 }}
newValue
Must 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.newValue
You can still use the defaultnewValue
This variable is used to access the new value.
Similar to read-only computing attributes, you can directly writeget
The code in the code block is written insubscript
Medium:
Subscript (Index: INT)-> int {// return the int type value that matches the input parameter}
The following code demonstratesTimesTable
The 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 exampleTimesTable
The struct creates an instance that represents three times the index value. Value3
As structConstructor
Initialize instance members with input parametersmultiplier
.
You can get the result through the affiliated script, suchthreeTimesTable[6]
. This sentence is accessedthreeTimesTable
And returns18
Or6
Of3
Times.
Note:
TimesTable
The 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 definednumberOfLegs
And initialize a dictionary instance that contains three pairs of key values.numberOfLegs
The dictionary storage value type is inferredDictionary<String, Int>
. After the dictionary instance is created, use the affiliated script to convert the integer value.2
The index assigned to the dictionary instance isbird
.
Note:
In the implementation of the dictionary affiliated script in swiftget
Partial return values areInt?
In the preceding examplenumberOfLegs
The 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 isnil
To delete the value of an index from the dictionary instance, you only need to assign the valuenil
You 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 definesMatrix
Struct to presentDouble
Type two-dimensional matrix.Matrix
The 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 } }}
Matrix
Provides a constructor for two input parameters. The input parameters arerows
Andcolumns
, Create a sufficient capacityrows * columns
NumberDouble
Type 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 appropriaterow
Andcolumn
To construct a newMatrix
Instance:
var matrix = Matrix(rows: 2, columns: 2)
In the above example, a new two-row and two-columnMatrix
Instance. Reading order from top left to bottom rightMatrix
Array instances in the instancegrid
Is 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 torow
Andcolumn
Affiliated scriptsmatrix
The 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 Matrix
The upper-right value is 1.5, and the sit-down value is 3.2:
[0.0, 1.5, 3.2, 0.0]
Matrix
Affiliated scriptsgetter
Andsetter
The attached script input parameters are also called.row
Andcolumn
Whether it is valid. To facilitate assertions,Matrix
ContainsindexIsValid
Member method, used to confirm the input parameterrow
Orcolumn
Whether 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