Subscript in Swfit

Posted by duvys on Mon, 20 Dec 2021 02:53:22 +0100

catalogue

Subscript syntax (subscript for subscript definition)

An example of subscript usage is dictionary

Subscript option (get set, if only get is implemented, it is a read-only attribute)

Type subscript (modified by adding static before subscript)

Summary:

Subscripts can be defined in classes, structs, and enumerations. They are shortcuts to access elements in a collection, list, or sequence. The index of the subscript can be used to set and obtain the value without calling the corresponding access method.

A type can define multiple subscripts, which can be overloaded through different index types. Subscripts are not limited to one dimension. You can define subscripts with multiple input parameters to meet the needs of user-defined types.

Subscript syntax (subscript for subscript definition)

Query the instance by passing in one or more index values in square brackets after the instance name// use?

Its syntax is similar to instance method syntax and computational attribute syntax. The subscript definition uses the {subscript} keyword. Similar to the instance definition method, it specifies one or more input parameters and a return type.

subscript(index: Int) -> Int {
    get {
      // Returns a value of the appropriate Int type
    }
    set(newValue) {
      // Perform the appropriate assignment
    }
}

The declaration of read-only subscript can be abbreviated by omitting the get keyword and the corresponding brace group (like read-only computational properties)

Read only subscript declaration. Same as read-only attribute
subscript(index: Int) -> Int {
    // Returns a value of the appropriate Int type
}

Example of using structure subscript syntax

struct TimesTable {
    let multiplier: Int

    Read only subscript value
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}

Created a TimesTable Example, used to represent the multiplication table of integer 3. The value 3 is passed to the constructor of the structure,
As instance member multiplier Value of.
let threeTimesTable = TimesTable(multiplier: 3)

print("six times three is \(threeTimesTable[6])")
// Print "six times three is 18"

An example of subscript usage is dictionary

Swift of Dictionary Type implementation subscripts are used for instance
var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
numberOfLegs["bird"] = 2

Subscript option (get set, if only get is implemented, it is a read-only attribute)

Subscripts can accept any number of input parameters, and these input parameters can be of any type. The return value of the subscript can also be of any type. Variable parameters can be used for subscripts, but in-out parameters cannot be used and default parameters cannot be provided.

//2D data structure
struct Matrix {
    let rows: Int, columns: Int   //Rows and columns of data
    var grid: [Double]            //One dimensional array after data expansion
    init(rows: Int, columns: Int) { //Constructor. All data in one-dimensional array is 0
        self.rows = rows 
        self.columns = columns
        grid = Array(repeating: 0.0, count: rows * columns)
    }
    func indexIsValid(row: Int, column: Int) -> Bool { //Judge whether it is in the construction interval
        return row >= 0 && row < rows && column >= 0 && column < columns
    }
    subscript(row: Int, column: Int) -> Double { //Write or read values in coordinate system
        get {
            Assertion to check subscript parameters row and column Whether the value of is valid.
            assert(indexIsValid(row: row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}

Using Matrix} provides a construction method that accepts two input parameters

initialization
var matrix = Matrix(rows: 2, columns: 2)

set value Use the subscript method to set the corresponding position value
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2

get value  The assertion will be triggered because [2, 2] More than matrix Scope of
let someValue = matrix[2, 2]

Type subscript (modified by adding static before subscript)

Instance subscripts are subscripts called on an instance of a specific type. You can also define a subscript called on the type itself. This kind of subscript is called type subscript. You can indicate a type subscript by writing the , static , keyword before the , subscript , keyword.

The class type can use the {class} keyword instead of} static, which allows subclasses to override the implementation of that subscript in the parent class. (similar to type attribute)

enum Planet: Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
    static subscript(n: Int) -> Planet {
        return Planet(rawValue: n)!
    }
}
let mars = Planet[4]
print(mars)  //mars

Summary:

1. Subscript syntax: similar to attribute. Use the keyword subscript to decorate Use in a dictionary like manner

2. Implement get and set methods inside syntax braces. If only get is implemented, it is a read-only property

3. Type subscript. Modify the subscript with static. Class can be used as the type subscript of class instead of static

        

reference resources http://www.swift51.com/swift5.1/02_language_guide/12_Subscripts.html

Topics: Swift