Swift unders contract script

Subsemic scripts can be defined in classes, structures, and enumerations as shortcuts to access objects, collections, or sequences without the need to invoke specific assignments and access methods for an instance.

For example, accessing elements in an array instance with a subsection script can be written like this, and accessing elements in a dictionary instance can be written like this.

Multiple underseed scripts can be defined for the same target, overloaded with different index value types, and the number of index values can be multiple.


Underseed script syntax and application

Grammar

The subsignment script allows you to access and assign an instance by passing one or more index values in square brackets after the instance.

The syntax is similar to a mixture of instance methods and computational properties.

Similar to the method of defining instances, defining subscript scripts uses subscript keywords to explicitly declare the entry (one or more) and return types.

Unlike the instance method, the underseed script can be set to read-write or read-only. This approach is a bit like the getter and setter of computational properties:

subscript(index: Int) -> Int {
    get {
        // 用于下标脚本值的声明
    }
    set(newValue) {
        // 执行赋值操作
    }
}

Instance 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 of the above program execution is:

100 除以 9 等于 11
100 除以 2 等于 50
100 除以 3 等于 33
100 除以 5 等于 20
100 除以 7 等于 14

In the example above, an instance of the division operation is created from the subexample structure. The value 100 is decrementer as a member of the incoming argument initialization instance of the structure constructor.

You can get the result by undersorting the script, such as division2, which is 100 divided by 2.

Instance 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 output of the above program execution is:

Sunday
Monday
Tuesday
Wednesday

Usage

Different underseed scripts have different meanings depending on the usage scenario.

Typically, subsequel scripts are shortcuts to access elements in a collection, list, or sequence.

You can freely implement the underlying script in your own specific class or structure to provide the appropriate functionality.

Swift's dictionary, for example, implements access to the values stored in its instance through a subsection script. Use a value of the same type as the dictionary index in the undersection script, and assign an value of a dictionary value type to this undersection 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 of the above program execution is:

["ant": 6, "bird": 2, "cat": 4, "spider": 8]

The example above defines a variable named numberOfLegs and literally initializes a dictionary instance with three pairs of key values in a dictionary. T he dictionary hold value type of numberOfLegs is inferred as Dictionary. After the dictionary instance is created, the integer value 2 is assigned to the dictionary instance's index as bird by the undersection script.


Underseed script options

The underlying script allows any number of in-indexes, and there is no limit to each entry type.

The return value of the underseed script can also be of any type.

The underseed script can use variable and variable parameters.

A class or structure can provide multiple subsigned script implementations according to its own needs, distinguish between types of incoming parameters when defining subsigned scripts, and automatically match the appropriate subsigned scripts when using subsigned scripts, which is the overload of subsigned scripts.

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 output of the above program execution is:

1.0
2.0
3.0
5.0

The Matrix structure provides a construction method for two incoming parameters, rows and columns, to create an array of Double types large enough to hold the number of rows and columns. I n order to store, the size of the array and the initial value of each element of the array are 0.0.

You can construct a new Matrix instance by passing in the right number of rows and columns.