subordinate 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 the specific assignment and access methods of the Instance. For example, accessing an element in an array instance with a subordinate script can be written so someArray[index]
that the elements in the Access dictionary (Dictionary) instance can be written like this someDictionary[key]
.
Multiple satellite 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
Subordinate scripting syntax
Satellite scripts allow 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, defining a satellite script uses subscript
the keyword to explicitly declare the in parameter (one or More) and the return type. Unlike instance methods, a subordinate script 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) { // 执行赋值操作 }}
newValue
Type must be the same as the return type defined by the satellite script. The same as the computed attribute is the parameter declaration of the set newValue
, even if not written, in the set code block can still use the default newValue
variable to access the new assigned Value.
As with read-only computed properties, You can write code that is supposed to be written in a get
code block directly subscript
:
subscript(index: Int) -> Int { // 返回与入参匹配的Int类型的值}
The following code demonstrates the use of a TimesTable
read-only satellite script in a struct that shows n times the number of incoming Integers.
struct TimesTable { let multiplier: Int subscript(index: Int) -> Int { return multiplier * index }}let threeTimesTable = TimesTable(multiplier: 3)println("3的6倍是\(threeTimesTable[6])")// 输出 "3的6倍是18"
In the example above, TimesTable
a struct was created to represent an instance of three times times the index Value. The numeric value 3
initializes the instance member as a struct body 构造函数
entry multiplier
.
You can get results by attaching a script, for example threeTimesTable[6]
. This sentence accesses the threeTimesTable
sixth element, which returns 18
or 6
times the second 3
.
Attention:
TimesTable
The example is based on a fixed mathematical Formula. It is not suitable for open Write permissions to threeTimesTable[someIndex]
perform assignment operations, which is why the satellite script is only defined as Read-only.
Satellite script usage
Depending on the usage scenario, different subordinate scripts also have different meanings. Typically a subordinate script is a shortcut that is used to access elements in a collection (collection), list, or sequence (sequence). You can freely implement satellite 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 a satellite script. Use the same type of value as the dictionary index in the satellite script, and assign a value of the dictionary value type to the subordinate script to set the value for the dictionary:
var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]numberOfLegs["bird"] = 2
The example above defines a numberOfLegs
variable named and initializes a dictionary instance with three pairs of key values with a dictionary literal. numberOfLegs
the dictionary store value type is inferred as Dictionary<String, Int>
. When the dictionary instance is created, the integer value is assigned to the location indexed by the dictionary instance by the satellite script 2
bird
.
For more information on dictionary (Dictionary) subordinate scripts, refer to reading and modifying dictionaries
Attention:
In the satellite script implementation of the dictionary in Swift, in the get
partial return value is Int?
, the dictionary in the above example numberOfLegs
is returned by the bottom of the one Int?
or "optional int", not each dictionary index can get an integer value, The result of access to an index that does not have an established value is the nil
same as if you want to delete the value under an index from the dictionary instance, just assign it to the index nil
.
Subordinate scripting options
The satellite script allows any number of parameter indexes, and there is no limit to the type of the incoming Parameter. The return value of a satellite script can also be of any type. A subordinate script 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 more than one satellite script implementation according to its own needs, when defining a satellite script is differentiated by the type of the import parameter, the use of satellite script will automatically match the appropriate satellite script implementation run, This is the overload of the subordinate script .
A subordinate script entry is the most common case, but you can define multiple subordinate script entry parameters as long as there is a suitable scenario. The following example defines a Matrix
struct that renders a Double
two-dimensional matrix of a type. A Matrix
subordinate script for a 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 && Colu MN >= 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 two-entry constructor, in which the arguments are rows
and columns
create an array of types sufficient to accommodate rows * columns
the number of arguments Double
. 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 row
column
construct a new instance by passing in the appropriate number of numbers Matrix
:
var matrix = Matrix(rows: 2, columns: 2)
In the example above, a new instance of two rows of two columns was created Matrix
. Array instances in the reading order from top left to bottom right Matrix
grid
are flattened storage of matrix two-dimensional arrays:
// grid = [0.0, 0.0, 0.0, 0.0] col0 col1row0 [0.0, 0.0,row1 0.0, 0.0]
Assigning a value to an row
instance expression with and to column
a subordinate script matrix
completes the assignment operation, and the subordinate script entry uses a comma-delimited
matrix[0, 1] = 1.5matrix[1, 0] = 3.2
The upper-right value of the above two statements is 让matrix
1.5, and the value of sitting down is 3.2:
[0.0, 1.5, 3.2, 0.0]
Matrix
Both the and of the subordinate scripts are getter
setter
called at the same time to determine whether the subordinate script is row
column
valid or Not. To facilitate assertions, Matrix
a member method named is included to indexIsValid
confirm that the entry row
or value causes the array to be out of column
bounds:
func indexIsValidForRow(row: Int, column: Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns}
Assertion triggers when a subordinate script is out of bounds:
let someValue = matrix[2, 2]// 断言将会触发,因为 [2, 2] 已经超过了matrix的最大长度
welcome-to-swift-12 Subordinate Script (subscripts)