IOS_Swift_Subscripts subscript script
1. Overview
Subscript, which can be defined in Class, structure, and enumeration. It is a collection, list, or sequence) element shortcut. You can use the index settings and obtain values of the subscript script without calling the corresponding access method. For example, you can use a subscript script to access elements in an Array instance to write someArray [index], and access elements in a Dictionary instance to write someDictionary [key].
//Dictionarypublic subscript (position: DictionaryIndex
) -> (Key, Value) { get }public subscript (key: Key) -> Value?
Multiple subscript scripts can be defined for one type and are overloaded by different index types. The subscript script is not limited to one dimension. You can define a subscript script with multiple input parameters to meet the requirements of custom types.
subscript(m:Int)->Intsubscript(m:Int, n:Int)->Intsubscript(name:String)->String
The subscript script allows you to input one or more index values in square brackets after the Instance name to access the instance. The syntax is similar to the combination of the instance method syntax and the computed attribute syntax. Similar to defining an instance, defining a subscript script uses the subscript keyword to specify one or more input parameters and return types. Different from the instance method, the subscript script can be set to read/write or read-only. This behavior is implemented by getter and setter, which is similar to the computing property:
Subscript (index: Int)-> Int {get {// return an appropriate Int type value} set (newValue) {// perform an appropriate value assignment operation }}
2. Code
enum Colors:Int{ case RED=1 case BLUE=2 subscript(m:Int)->Int{ return self.rawValue*m } subscript(m:Int, n:Int)->Int{ return self.rawValue*m*n } subscript(name:String)->String{ return name:(name) value=(self.rawValue) }}print(subscript--->(Colors.RED[2]))print(subscript (m:Int, n:Int)--->(Colors.BLUE[2,3]))print(subscript name--->(Colors.BLUE[name]))