Subscript Script
Subscript scripts can be defined in the classes (class), struct (structure), and enumeration (enumeration) targets , which can be thought of as access to the collection (collection), list, or sequence (sequence shortcut , using the index of the subscript script to set and get values, you do not need to invoke the instance's specific assignment and access methods. For example, using the subscript script to access elements in an array instance can be written someArray[index]
so that the elements in the Access Dictionary (Dictionary) instance can be written someDictionary[key]
like this.
Basic Syntax
Subscript (index:int), int{ get { // return INT operation here// returns 0 } set { C14/>print (NewValue) //The assignment operation here can get the position according to the index parameter and then get the newvalue to assign the value } }
The subscript script has no restrictions on the incoming parameter type, there are no restrictions on the number of parameters, and there are no restrictions on the return value, but the incoming parameter cannot be a in-out type, nor can it be set to a default value. In some cases, there can be multiple subscript scripts in a class or a struct, and the primary way to differentiate them is to pass in the parameters and return values.
struct Timestable {let multiplier:int ///This is a read-only table Script subscript (index:int), Int { return Multiplier * Index } }var twotimestable = timestable (multiplier:2) print ("2 of 8 times Times is: \ (Twotimestable[8])")//Print out: " 2 of 8 times Times is: 16 "
Swift Native type subscript script
Subscript scripts are typically used to access a collection, sequence, or list of shortcuts, such as a dictionary in Swift:
Create a dictionary var numberoflegs = ["Spider": 6, "Bird": 2, "cat": 4]//add a key value via subscript script numberoflegs["fish"] = 0//Modify a value by using the subscript script numb Eroflegs["spider"] = 8//Returns a value by the Subscript script print (numberoflegs["dog"])//printed out: "nil" //This proves that the following table script in the dictionary returns a nullable type
Learn swift--subscript script