Below the Swift tutorials _swift

Source: Internet
Author: User
Tags assert instance method

Classes, structs, and enum types can be called to call a group or a member element in a sequence by defining the subscript. The subscript index makes it easy to retrieve and set the values, without requiring additional action. For example, you can use Somearray[index to access the elements in an array, or Somedictionary[key] to index the dictionary.

You can define multiple subscripts for a type, and the appropriate subscript overload to set the corresponding value based on the index passed to the subscript. Subscript can be defined as one-dimensional, and can be defined as multidimensional, multiple parameters.

1, the next slogan law

Subscript allows you to retrieve an element by adding one or more values in parentheses after the instance name. Syntax and method syntax are similar to property syntax by using the subscript key definition, one or more input parameters, and a return value. Unlike the instance method, the subscript can be either read or write-readable or read-only. This behavior is unicom through a getter and setter statement, just like a computed property.

Copy Code code as follows:

Subscript (index:int)-> Int {
get {
Return a appropriate subscript value here
}
Set (NewValue) {
Perform a suitable setting action here
}
}

The type of the newvalue is the same as the type returned by the subscript. As with the computed property, you can choose not to specify the setter's parameters, because when you do not specify, the default parameter newvalue is supplied to the setter.

As with computed properties, read-only subscripts do not require get keywords:

Copy Code code as follows:

Subscript (index:int)-> Int {
Return a appropriate subscript value here
}

Here is an implementation of a read-only subscript that defines a timestable structure to represent the multiplier of an integer:

Copy Code code as follows:

struct Timestable {
Let Multiplier:int
Subscript (index:int)-> Int {
Return multiplier * Index
}
}
Let threetimestable = timestable (multiplier:3)
println ("six times three is \ (Threetimestable[6])")
Prints "six times three is 18"

In this example, the instance timestable is created as a 3 times-fold number, which is set by the value 3 passed in for the multiplier parameter at initialization time.

Attention:

The number of tables is set according to a particular mathematical rule, so a new value should not be set for the Threetimetable[someindex] element, so the subscript for the timestable is defined as read-only.

2, the use of subscript

The exact meaning of the subscript is determined by the context in which it was used. Subscript is used primarily as a shortcut to elements of collections, lists, and sequences. You are free to define the subscript you need for your class or structure.

For example, the subscript implemented by the dictionary type in Swift is to set and retrieve the values in the dictionary instance. You can set multiple values by giving the keywords and values in the subscript respectively, or you can set the values of a single dictionary by subscript:

Copy Code code as follows:

var numberoflegs = ["Spider": 8, "Ant": 6, "Cat": 4]
numberoflegs["Bird"] = 2

The above example defines a variable numberoflegs, which is then initialized by a key value pair. The type of Numberoflegs is the dictionary type dictionary<string, int>. After the dictionary was created, the example uses the subscript assignment method to add a key "bird" and an int value of type String 2 to the dictionary.

For more information on dictionaries, refer to the chapter on accessing and modifying dictionaries

Attention:

The dictionary type in swift implements a key-value pair subscript that is an optional type. For the Numberoflges dictionary, the returned value is int, which is the optional int value. This method of using an optional type subscript for a dictionary shows that not all keys have corresponding values. You can also delete this key by assigning a value to the key nil.

3, subscript options

Subscript can receive any number of arguments, and the types of parameters can vary. The subscript can also return any type of value. The subscript can use variable parameters or variable parameters, but cannot use input or output parameters or provide values for default parameters.

A class or struct can implement various subscript methods as needed, and you can use the appropriate subscript to return the desired value by using the parameters in the brackets as needed. The definition of this multiple subscript is called a subscript overload.

Of course, the most common subscript usage is a single parameter, or you can define the subscript for multiple parameters. The following example shows a matrix matrices structure that contains a two-dimensional double value. The subscript of a matrix structure consists of two shaping parameters:

Copy Code code as follows:

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) + column] = newvalue
}
}
}

Matrix matrices provide an initialization method that uses two parameters rows and columns, and then creates an array to store the value rows*columns of type Double. The position in each matrix is set to an initial value of 0.0. This is done by passing the initial value of 0.0 and a set of lengths to the array initialization method. The initialization method of an array is described in more detail in: Creating and initializing an array.

You can pass two parameters row and column to complete the initialization of the matrix:

Copy Code code as follows:

var matrix = matrix (Rows:2, Columns:2)

The initialization above creates an instance of matrix matrices with two rows of two columns. The grid array of this matrix instance looks flat, but it is actually a one-dimensional storage form of the matrix from top left to bottom right.

The values in the matrix can be set by using subscripts that contain row and column and commas:

Copy Code code as follows:

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

The two statements invoke the subscript's setter method to assign values 1.5 and 3.2 to the upper-right and lower-left corners of the two elements, respectively.

The getter and setter methods for the subscript of a matrix include an assertion statement to check whether the subscript row and column are valid. The Indexisvalid method is used to determine whether row and column are within the bounds of the matrix:

Copy Code code as follows:

Func Indexisvalidforrow (Row:int, column:int)-> Bool {
Return row >= 0 && row < rows && column >= 0 && column < columns
}

If the access matrix crosses the line, the assertion is triggered:

Copy Code code as follows:

Let somevalue = matrix[2, 2]
This triggers a assert, because [2, 2] is outside of the matrix bounds

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.