this blog post for the original, reproduced please specify the source!
http://blog.csdn.net/zimo2013/article/details/50177691
1. Overview
Subscript script subscript, which can be defined in classes (Class), structs (structure), and enumerations (enumeration), is a shortcut to an element in a collection (collection), list, or sequence (sequence). You can use the index of the subscript script to set and get the value, no need to call the corresponding access method. For example, using the subscript script to access an element in an array instance can write Somearray[index], accessing the elements in the dictionary instance to write Somedictionary[key].
Dictionarypublic subscript (Position:dictionaryindex<key, value>) (key, Value) {get}public subscript (key : Key), Value?
A type can define multiple subscript scripts that are overloaded by different index types. Subscript scripts are not limited to one-dimensional, you can define subscript scripts with multiple incoming parameters to meet the needs of custom types.
Subscript (M:int)->intsubscript (M:int, N:int)->intsubscript (name:string)->string
The subscript script allows you to access an instance by passing in one or more index values in brackets after the instance name. Syntax is similar to the mixture of instance method syntax and computed property syntax. Similar to defining an instance method, the subscript script is defined using the Subscript keyword, specifying one or more entry and return types. Unlike an instance method, the subscript script can be set to read-write or read-only. This behavior is implemented by getter and setter, somewhat analogous to computed properties:
Subscript (index:int), int { get { ///Returns a value of the appropriate Int type } set (NewValue) { //perform the appropriate 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"])
ios_swift_subscripts Subscript Script