Swift-Subscripts and swiftsubscripts
A subscript script can be defined in objects such as Class, Struct, and enumeration. It can be considered as a shortcut to access a set, list, or sequence, you do not need to call the instance's specific assignment and access methods to set and obtain values using the index of the subscript script. Multiple subscript scripts can be defined for the same target, which can be overloaded by different index value types. The subscript script is not limited to a single latitude, you can define scripts for multiple input parameters to meet the requirements of custom types.
1. subscript script syntax
The subscript script allows you to access and assign values to an instance by inputting one or more index values in square brackets after the instance. The syntax is similar to the mixing of instance methods and computing attributes. Similar to defining an instance, defining a subscript script uses the subscript keyword to display declared input parameters (one or more) and return types. Different from the instance method, the subscript script can be set to read/write or read-only. This method is a bit like getter and setter of the calculation attribute:
Subscript (index: Int)-> Int {get {// return the int type value that matches the input parameter} set (newValue) {// execute the value assignment parameter }}
The newValue type must be the same as the return type defined by the subscript script. The same as the computing attribute is that even if newValue is not written, the default newValue variable can still be used in the set code block to access the newly assigned value. Similar to the read-only computing attribute, you can directly write the code originally written in the get code block in subscript:
Subscript (index: Int)-> Int {// return the int type value that matches the input parameter}
2. subscript script usage
Different subscripts have different meanings based on the scenario. A subscript script is usually used to access a set. The Shortcut of the elements in the list or sequence is as follows. You can freely implement subscript scripts in your own specific classes or struct to provide appropriate functions.
For example, the Swift Dictionary allows you to use the subscript script to access the values stored in the instance.
Var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] numberOfLegs ["bird"] = 4 // save Value
3. subscript script options
The subscript script allows any number of input parameter indexes, and there is no limit on the index type of each input parameter. The Return Value of the subscript script can also be of any type.