Swift subscript script
Subscript scripts can be defined in targets such as classes, structures, and enumerations. They can be considered as shortcuts to access objects, collections, or sequences without calling instances. specific assignment and access methods.
For example, to use a subscript script to access elements in an array (Array) instance, you can write someArray[index], and to access elements in a dictionary (Dictionary) instance, you can write someDictionary[key].
Multiple subscript scripts can be defined for the same target, overloaded through different index value types, and the number of index values can be multiple.
Subscript script syntax and application
Syntax
Subscript script allows you to pass in one or more index values in square brackets after the instance to access and assign values to instances.
The syntax is similar to a mix of instance methods and computed properties.
Similar to defining instance methods, defining subscript scripts uses the subscript keyword to explicitly declare the input parameters (one or more) and return types.
Different from instance methods, subscript scripts can be set to read-write or read-only. This method is a bit like the getter and setter of computed properties:
subscript(index: Int) -> Int { get { // 用于下标脚本值的声明 } set(newValue) { // 执行赋值操作 } }
Example 1
import Cocoa struct subexample { let decrementer: Int subscript(index: Int) -> Int { return decrementer / index } } let division = subexample(decrementer: 100) print("100 除以 9 等于 \(division[9])") print("100 除以 2 等于 \(division[2])") print("100 除以 3 等于 \(division[3])") print("100 除以 5 等于 \(division[5])") print("100 除以 7 等于 \(division[7])")
The output result of the execution of the above program is:
100 除以 9 等于 11 100 除以 2 等于 50 100 除以 3 等于 33 100 除以 5 等于 20 100 除以 7 等于 14
In the above example, through The subexample structure creates an instance of the division operation. The value 100 is passed as a parameter to the structure constructor to initialize the instance member decrementer.
You can get the result by subscripting the script, for example division[2] is 100 divided by 2.
Example 2
import Cocoa class daysofaweek { private var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "saturday"] subscript(index: Int) -> String { get { return days[index] // 声明下标脚本的值 } set(newValue) { self.days[index] = newValue // 执行赋值操作 } } } var p = daysofaweek() print(p[0]) print(p[1]) print(p[2]) print(p[3])
The execution output of the above program is:
Sunday Monday Tuesday Wednesday
Usage
The subscript script also has different meanings depending on the usage scenario.
Usually subscript scripts are a shortcut for accessing elements in a collection, list, or sequence.
You are free to implement subscript scripts in your own specific classes or structures to provide appropriate functionality.
For example, Swift's Dictionary implements access operations to the values stored in its instances through subscript scripts. Use the same type of value as the dictionary index in the subscript script, and assign a value of dictionary value type to the subscript foot to set the value for the dictionary:
import Cocoa var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] numberOfLegs["bird"] = 2 print(numberOfLegs)
The output result of the above program execution is:
["ant": 6, "bird": 2, "cat": 4, "spider": 8]
The above example defines a variable named numberOfLegs and uses a dictionary literal to initialize a dictionary instance containing three pairs of key values. The dictionary storage value type of numberOfLegs is inferred as Dictionary
Subscript script option
The subscript script allows any number of input parameter indexes, and there is no limit on each input parameter type.
The return value of the subscript script can also be of any type.
Subscript scripts can use variable parameters and variable parameters.
A class or structure can provide multiple subscript script implementations according to its own needs. When defining a subscript script, they are distinguished by the type of the parameters passed in. When using the subscript script, the appropriate subscript will be automatically matched. The script is run, which is the overload of the subscript script.
import Cocoa struct Matrix { let rows: Int, columns: Int var print: [Double] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns print = Array(count: rows * columns, repeatedValue: 0.0) } subscript(row: Int, column: Int) -> Double { get { return print[(row * columns) + column] } set { print[(row * columns) + column] = newValue } } } // 创建了一个新的 3 行 3 列的Matrix实例 var mat = Matrix(rows: 3, columns: 3) // 通过下标脚本设置值 mat[0,0] = 1.0 mat[0,1] = 2.0 mat[1,0] = 3.0 mat[1,1] = 5.0 // 通过下标脚本获取值 print("\(mat[0,0])") print("\(mat[0,1])") print("\(mat[1,0])") print("\(mat[1,1])")
The execution output of the above program is:
The1.0 2.0 3.0 5.0
Matrix structure provides a constructor with two parameters passed in. The two parameters are rows and columns, creating a Double type array that is enough to accommodate the number of rows * columns. For storage, set the size of the array and initialize each element of the array to 0.0.
You can construct a new Matrix instance by passing in the appropriate number of rows and columns.