Swift subscript script

Release date:2021-12-15 Update date:2023-12-08 Editor:admin View counts:2596


Swift subscript script

Subscript scripts can be defined in Class, structure, and enumeration targets and can be thought of as shortcuts to access objects, collections, or sequences, eliminating the need to call instance-specific assignments andaccess methods.

For example, using subscript scripts to access elements in an Array instancecan be written as follows someArray[index] the elements in the access dictionary (Dictionary) instance can be written as follows someDictionary[key] .

Multiple subscript scripts can be defined for the same target, overloaded bydifferent types of index values, and the number of index values can be multiple.

Subscript script syntax and its application


The subscript script allows you to access and assign an instance by passing one or more index values in square brackets at the end of the instance.

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

Similar to the method of defining an instance, defining a subscript script uses the subscript keyword to explicitly declare input parameters (one or more) and return types.

Unlike the instance method, the subscript script can be set to read-write orread-only. This approach is a bit like a computational attribute. getter and setter :

subscript(index: Int) -> Int {
    get {
        // Declaration for subscript script values
    set(newValue) {
        // Performing assignment operations

Example 1

import Cocoa

struct subexample {
    let decrementer: Int
    subscript(index: Int) -> Int {
        return decrementer / index
let division = subexample(decrementer: 100)

print("100 divided by 9 is equal to \(division[9])")
print("100 divided by 2 is equal to \(division[2])")
print("100 divided by 3 is equal to \(division[3])")
print("100 divided by 5 is equal to \(division[5])")
print("1100 divided by 7 is equal to \(division[7])")

The output of the above program execution is as follows:

100 divided by 9 equals 11
100 divided by 2 equals 50
100 divided by 3 equals 33
100 divided by 5 equals 20
100 divided by 7 equals 14

In the above example, through the subexample structure creates an example of a division operation. The value 100 initializes the instance member as a parameter passed in as the constructor of the structure decrementer .

You can get the results by subscript, such as division[2] that 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]   // Declare the value of the subscript script
        set(newValue) {
            self.days[index] = newValue   // Performing assignment operations
var p = daysofaweek()


The output of the above program execution is as follows:



Subscript scripts also have different meanings according to different usage scenarios.

Typically, subscript scripts are shortcuts to access elements in a collection , list , or sequence (sequence).

You are free to implement subscript scripts to provide appropriate functionality in your own specific classes or structures.

For example, Swift’s dictionary implements access to values stored in its instance through subscript scripts. Use the same type of valueas the dictionary index in the subscript script, and assign the value of a 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


The output of the above program execution is as follows:

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

The above example defines a file named numberOfLegs and initializes a dictionary instance containing three pairs of key values with a dictionary literal numberOfLegs the type of dictionary stored value is inferred as``Dictionary`` . After the dictionary instance is created, the integer value 2 is assigned to the index of the dictionary instance by subscript script bird in the position of.

Subscript script option

The subscript script allows any number of input parameters, and there is no limit to each input parameter type.

The return value of the subscript 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, it is distinguished by the type of parameters passed in, and when using the subscript script, it automatically matches the appropriate subscript script to run. This is the overloading 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(repeating: 0.0, count: rows * columns)
    subscript(row: Int, column: Int) -> Double {
        get {
            return print[(row * columns) + column]
        set {
            print[(row * columns) + column] = newValue
// Created a new Matrix instance with 3 rows and 3 columns
var mat = Matrix(rows: 3, columns: 3)

// Set values through subscript scripts
mat[0,0] = 1.0
mat[0,1] = 2.0
mat[1,0] = 3.0
mat[1,1] = 5.0

// Obtain values through subscript scripts
The output result of the above program execution is:


The Matrix structure provides a constructor for two incoming parameters, which are rows and columns to create a sufficient capacity rows* columns number of Double type array. To store, change the size of the array and the initial value of each element of the array to 0.0.

You can pass in the appropriate row and column to construct a new Matrix instance

Powered by TorCMS (https://github.com/bukun/TorCMS).