Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence. You use subscripts to set and retrieve values by index without needing separate methods for setting and retrieval. For example, you access elements in an Array instance as someArray[index] and elements in a Dictionary instance as someDictionary[key]. 类,结构体和枚举可以定义附属脚本,它可以快捷访问集合,列表和序列的成员。你可以应用附属脚本index来设置和查找值而不需要独立的方法来设置和检索。例如,你可以访问一个数组实例的元素通过【】以及字典的元素通过【】。 You can define multiple subscripts for a single type, and the appropriate subscript overload to use is selected based on the type of index value you pass to the subscript. Subscripts are not limited to a single dimension, and you can define subscripts with multiple input parameters to suit your custom type’s needs. 你可以对一种类型定义多种脚本,通过索引值类型的不同来进行重载。脚本不限于单一类型,你可以输入多个类型来适应不同类型的需要。 附属脚本的语法 Subscripts enable you to query instances of a type by writing one or more values in square brackets after the instance name. Their syntax is similar to both instance method syntax and computed property syntax. You write subscript definitions with the subscript keyword, and specify one or more input parameters and a return type, in the same way as instance methods. Unlike instance methods, subscripts can be read-write or read-only. This behavior is communicated by a getter and setter in the same way as for computed properties: 附属脚本使你能够查询一个类型的实例通过在一对方括号里边写入一个或者多个值。他们的语法有点类似实例方法和计算属性的混合。你定义附属脚本用subscript关键字。尤其是一个或者多个参数,一个返回值同样的方式类似于实例方法。不像实例方法,附属脚本可以是只读或者已读。这种方式又与计算属性的set和get方法类似。 The type of newValue is the same as the return value of the subscript. As with computed properties, you can choose not to specify the setter’s (newValue) parameter. A default parameter called newValue is provided to your setter if you do not provide one yourself. newValue的类型与附属脚本的返回值一致。像计算属性一样,你可以不指定setter方法的参数,set的默认值是newValue,如果你不指定的话。 As with read-only computed properties, you can simplify the declaration of a read-only subscript by removing the get keyword and its braces: 像计算属性的只读一样,你可以简单设置只读,而移调get关键字和综括号。 例如: 解释:只要你一写综括号,他就去类型里边去寻找对应的附属脚本了,对应set或get。 附属脚本用法 The exact meaning of “subscript” depends on the context in which it is used. Subscripts are typically used as a shortcut for accessing the member elements in a collection, list, or sequence. You are free to implement subscripts in the most appropriate way for your particular class or structure’s functionality. 附属脚本是真是的含义需要依赖上下文。已经应用附属脚本的类有数组,集合等。你可以在你的类或者结构体里边利用附属脚本来定义自己的功能。 For example, Swift’s Dictionary type implements a subscript to set and retrieve the values stored in a Dictionary instance. You can set a value in a dictionary by providing a key of the dictionary’s key type within subscript brackets, and assigning a value of the dictionary’s value type to the subscript: 例如:swift的字典实现了利用键来给存储值赋值。