Classes, structs, and enumerations can define subscripts, and he can quickly and easily access the elements of a collection (set,array,dict), and you can make use of subscripts to get and set the collection elements. You can define multiple subscripts for a type, which can be overloaded by the different index value types, and the number of indexed values may be multiple.
Grammar
Look at an example first
Subscript (index:int), Int { get { // return an appropriate Subscript valuehere } set(newvalue) { // perform A suitable setting actionhere }}
It allows you to access and assign values to an instance by passing in one or more index values in the brackets behind the instance. Syntax is similar to the blending of instance methods and computed properties. Similar to defining an instance method, defining subscript uses the SUBSCRIPT keyword to explicitly declare the in parameter (one or more) and the return type. Unlike instance methods, subscripts can be set to read-write or read-only. This approach is somewhat like the getter and setter of computed properties:
The type of newvalue must be the same as the return type defined by subscript. The same as the computed attribute is the parameter declaration of the set newvalue even if not written, the default newvalue variable can still be used to access the newly assigned value in the set code block. As with read-only computed properties, you can write the code that should be written in the get code block directly in subscript:
Subscript (index:int), Int { //
Swift learning "Swift Programming Tour---subscripts subscript (16)