Latest web development tutorials

Swift subscript script

Subscript script can be defined in the class (Class), structure (structure) and enumeration (enumeration) of these objectives can be considered access to the object, a collection of shortcuts or sequences do not need to call the instance-specific assignments and access method.

For example, a script with access to an array index (Array) instance element can write someArray [index], element access the dictionary (Dictionary) instance can write someDictionary [key].

For the same objective can define multiple subscript script, different types of index values ​​to be overloaded, and the number of index values ​​may be plural.

Subscript script syntax and Application


Subscript script allows you to index values ​​by passing one or more of the following instances in square brackets to access and assignment for instance.

The syntax is similar to mixing instance methods and computational property.

And the definition of an instance method is similar to the definition of subscript subscript script keywords explicitly declare the Senate (one or more) and return type.

And examples of different methods is subscript script can be set to read-write or read-only. In this way a bit like getter and setter computational 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 above program execution output is:

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

In the above example, by subexample structure creates an instance of a division operation. A value of 100 as the structure constructor argument passed to initialize instance member decrementer.

You can get the result by the subscript script, such as division [2] is 100 divided by two.

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()


The above program execution output is:



According to different usage scenarios subscript script also has a different meaning.

Typically subscript script is used to access the collection (collection), the shortcut list (list) or sequence (sequence) of elements.

You are free to implement index script in your own particular class or struct to provide the appropriate functionality.

For example, Swift dictionary (Dictionary) to achieve the access operation by the subscript script instance value stored in it. The next standard value used in the script and dictionary index of the same type, and the value of a dictionary value type is assigned to the index value set foot to the dictionary:

import Cocoa

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


The above program execution output is:

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

The example defines a variable named numberOfLegs and use a dictionary literal to initialize an instance of the dictionary contains three pairs of keys. numberOfLegs dictionary stored value type inferred Dictionary . After the dictionary instance is created by the way the script subscript 2 integer value assigned to the dictionary instance index for the bird's location.

Subscript script options

Subscript script allows any number of parameters into the index, and each type is also no limit to the Senate.

Return Value index of the script can be any type.

Subscript script can use variable parameters and variable parameters.

A class or structure can be according to their own needs to provide more of the following standard scripts, when defining the subscript script by passing parameters to distinguish the type, it will automatically match the appropriate subscript scripts runtime subscript script, which isoverloaded 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

// 通过下标脚本获取值

The above program execution output is:


Matrix structure provides a two constructor arguments passed two parameters are the rows and columns, create an array of type Double enough to accommodate the number of rows * columns. For storage, the size of each element of the array and the array initial value of 0.0.

You can construct a new Matrix instance by passing the appropriate row and column of the number.