Skip to content

Commit eac7a3f

Browse files
Merge pull request #1355 from SwiftGGTeam/1333-languageguide-subscriptsmd
1333 languageguide subscriptsmd
2 parents 80f3dca + 8b4bf74 commit eac7a3f

File tree

1 file changed

+47
-156
lines changed

1 file changed

+47
-156
lines changed

swift-6-beta.docc/LanguageGuide/Subscripts.md

Lines changed: 47 additions & 156 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,28 @@
1-
<!--
2-
要翻译的文件:https://github.com/SwiftGGTeam/the-swift-programming-language-in-chinese/blob/swift-6-beta-translation/swift-6-beta.docc/LanguageGuide/Subscripts.md
3-
Swift 文档源文件地址:https://docs.swift.org/swift-book/documentation/the-swift-programming-language/subscripts
4-
翻译估计用时:⭐️⭐️⭐️⭐️
5-
-->
61

7-
# Subscripts
2+
# 下标
83

9-
Access the elements of a collection.
4+
访问集合的元素
105

11-
Classes, structures, and enumerations can define *subscripts*,
12-
which are shortcuts for accessing the member elements of a collection, list, or sequence.
13-
You use subscripts to set and retrieve values by index without needing
14-
separate methods for setting and retrieval.
15-
For example, you access elements in an `Array` instance as `someArray[index]`
16-
and elements in a `Dictionary` instance as `someDictionary[key]`.
6+
**下标**可以定义在类、结构体和枚举中,是访问集合、列表或序列中元素的快捷方式。可以使用下标的索引设置和获取值,而不需要再调用对应的存取方法。举例来说,用下标访问一个 `Array` 实例中的元素可以写作 `someArray[index]`,访问 `Dictionary` 实例中的元素可以写作 `someDictionary[key]`
177

18-
You can define multiple subscripts for a single type,
19-
and the appropriate subscript overload to use is selected
20-
based on the type of index value you pass to the subscript.
21-
Subscripts aren't limited to a single dimension,
22-
and you can define subscripts with multiple input parameters
23-
to suit your custom type's needs.
8+
一个类型可以定义多个下标,系统会根据索引值的类型自动选择对应的下标重载。下标不限于一维,你可以定义具有多个入参的下标来满足自定义类型的需求。
249

2510
<!--
2611
TODO: this chapter should provide an example of subscripting an enumeration,
2712
as per Joe Groff's example from rdar://16555559.
2813
-->
2914

30-
## Subscript Syntax
15+
## 下标语法
3116

32-
Subscripts enable you to query instances of a type
33-
by writing one or more values in square brackets after the instance name.
34-
Their syntax is similar to both instance method syntax and computed property syntax.
35-
You write subscript definitions with the `subscript` keyword,
36-
and specify one or more input parameters and a return type,
37-
in the same way as instance methods.
38-
Unlike instance methods, subscripts can be read-write or read-only.
39-
This behavior is communicated by a getter and setter
40-
in the same way as for computed properties:
17+
下标允许你通过在实例名称后面的方括号中传入一个或者多个索引值来对实例进行查询。它的语法类似于实例方法语法和计算型属性语法。定义下标使用 `subscript` 关键字,与定义实例方法类似,都是指定一个或多个输入参数和一个返回类型。与实例方法不同的是,下标可以设定为读写或只读。这种行为由 getter 和 setter 实现,类似计算型属性:
4118

4219
```swift
4320
subscript(index: Int) -> Int {
4421
get {
45-
// Return an appropriate subscript value here.
22+
// 返回一个适当的 Int 类型的值
4623
}
4724
set(newValue) {
48-
// Perform a suitable setting action here.
25+
// 执行适当的赋值操作
4926
}
5027
}
5128
```
@@ -68,19 +45,13 @@ subscript(index: Int) -> Int {
6845
```
6946
-->
7047

71-
The type of `newValue` is the same as the return value of the subscript.
72-
As with computed properties, you can choose not to specify
73-
the setter's `(newValue)` parameter.
74-
A default parameter called `newValue` is provided to your setter
75-
if you don't provide one yourself.
48+
`newValue` 的类型与下标的返回值类型相同。如同计算型属性,可以不指定 setter 的参数(`newValue`)。如果不指定参数,setter 会提供一个名为 `newValue` 的默认参数。
7649

77-
As with read-only computed properties,
78-
you can simplify the declaration of a read-only subscript
79-
by removing the `get` keyword and its braces:
50+
如同只读计算型属性,对于只读下标的声明,你可以通过省略 `get` 关键字和对应的大括号组来进行简写:
8051

8152
```swift
8253
subscript(index: Int) -> Int {
83-
// Return an appropriate subscript value here.
54+
// 返回一个适当的 Int 类型的值
8455
}
8556
```
8657

@@ -97,8 +68,7 @@ subscript(index: Int) -> Int {
9768
```
9869
-->
9970

100-
Here's an example of a read-only subscript implementation,
101-
which defines a `TimesTable` structure to represent an *n*-times-table of integers:
71+
下面代码演示了只读下标的实现,这里定义了一个 `TimesTable` 结构体,用来表示对应整数的乘法表:
10272

10373
```swift
10474
struct TimesTable {
@@ -109,7 +79,7 @@ struct TimesTable {
10979
}
11080
let threeTimesTable = TimesTable(multiplier: 3)
11181
print("six times three is \(threeTimesTable[6])")
112-
// Prints "six times three is 18"
82+
// 打印“six times three is 18
11383
```
11484

11585
<!--
@@ -128,33 +98,18 @@ print("six times three is \(threeTimesTable[6])")
12898
```
12999
-->
130100

131-
In this example, a new instance of `TimesTable` is created
132-
to represent the three-times-table.
133-
This is indicated by passing a value of `3` to the structure's `initializer`
134-
as the value to use for the instance's `multiplier` parameter.
101+
在上例中,创建了一个 `TimesTable` 实例,用来表示整数 `3` 的乘法表。数值 `3` 被传递给结构体的构造函数,作为实例成员 `multiplier` 的值。
135102

136-
You can query the `threeTimesTable` instance by calling its subscript,
137-
as shown in the call to `threeTimesTable[6]`.
138-
This requests the sixth entry in the three-times-table,
139-
which returns a value of `18`, or `3` times `6`.
103+
你可以通过下标访问 `threeTimesTable` 实例,例如上面演示的 `threeTimesTable[6]`。这条语句查询了乘法表中 `3` 的第六个元素,返回 `3``6` 倍即 `18`
140104

141-
> Note: An *n*-times-table is based on a fixed mathematical rule.
142-
> It isn't appropriate to set `threeTimesTable[someIndex]` to a new value,
143-
> and so the subscript for `TimesTable` is defined as a read-only subscript.
105+
>注意:
106+
`TimesTable` 例子基于一个固定的数学公式。将 `threeTimesTable[someIndex]` 进行赋值操作并不合适,因此下标定义为只读的。
144107

145-
## Subscript Usage
108+
## 下标用法
146109

147-
The exact meaning of “subscript” depends on the context in which it's used.
148-
Subscripts are typically used as a shortcut for accessing
149-
the member elements in a collection, list, or sequence.
150-
You are free to implement subscripts in the most appropriate way for
151-
your particular class or structure's functionality.
110+
“下标”的确切含义取决于使用场景。下标通常用作访问集合、列表或序列中的成员元素的快捷方式。你可以针对自己特定的类或结构体功能来以最恰当的方式实现下标。
152111

153-
For example, Swift's `Dictionary` type implements a subscript
154-
to set and retrieve the values stored in a `Dictionary` instance.
155-
You can set a value in a dictionary
156-
by providing a key of the dictionary's key type within subscript brackets,
157-
and assigning a value of the dictionary's value type to the subscript:
112+
例如,Swift 的 `Dictionary` 类型实现下标用于对实例中储存的值进行存取操作。为字典设值时,在下标中使用和字典的键类型相同的键,并把一个和字典的值类型相同的值赋给这个下标:
158113

159114
```swift
160115
var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
@@ -170,38 +125,18 @@ numberOfLegs["bird"] = 2
170125
```
171126
-->
172127

173-
The example above defines a variable called `numberOfLegs`
174-
and initializes it with a dictionary literal containing three key-value pairs.
175-
The type of the `numberOfLegs` dictionary is inferred to be `[String: Int]`.
176-
After creating the dictionary,
177-
this example uses subscript assignment to add
178-
a `String` key of `"bird"` and an `Int` value of `2` to the dictionary.
179-
180-
For more information about `Dictionary` subscripting,
181-
see <doc:CollectionTypes#Accessing-and-Modifying-a-Dictionary>.
182-
183-
> Note: Swift's `Dictionary` type implements its key-value subscripting
184-
> as a subscript that takes and returns an *optional* type.
185-
> For the `numberOfLegs` dictionary above,
186-
> the key-value subscript takes and returns a value of type `Int?`,
187-
> or “optional int”.
188-
> The `Dictionary` type uses an optional subscript type to model the fact that
189-
> not every key will have a value, and to give a way to delete a value for a key
190-
> by assigning a `nil` value for that key.
191-
192-
## Subscript Options
193-
194-
Subscripts can take any number of input parameters,
195-
and these input parameters can be of any type.
196-
Subscripts can also return a value of any type.
197-
198-
Like functions,
199-
subscripts can take a varying number of parameters
200-
and provide default values for their parameters,
201-
as discussed in <doc:Functions#Variadic-Parameters>
202-
and <doc:Functions#Default-Parameter-Values>.
203-
However, unlike functions,
204-
subscripts can't use in-out parameters.
128+
上面的示例定义了一个名为 `numberOfLegs` 的变量,并用一个包含三对键值的字典字面量初始化它。`numberOfLegs` 字典的类型推断为 `[String: Int]`。创建字典后,此示例使用下标赋值将 `String` 类型的键 `bird``Int` 类型的值 `2` 添加到字典中。
129+
130+
更多关于 `Dictionary` 下标的信息请参考 <doc:CollectionTypes#Accessing-and-Modifying-a-Dictionary>.
131+
132+
>注意:
133+
>Swift 的 `Dictionary` 类型的下标接受并返回_可选_类型的值。对于上面的 `numberOfLegs` 字典通过下标返回的是一个 `Int?` 或者说“可选的 int”。`Dictionary` 类型之所以如此实现下标,是因为不是每个键都有对应的值,同时这也提供了一种通过键删除对应值的方式,只需将键对应的值赋值为 nil 即可。
134+
135+
## 下标选项
136+
137+
下标可以接受任意数量的入参,并且这些入参可以是任何类型。下标的返回值也可以是任意类型。
138+
139+
与函数一样,下标可以接受不同数量的参数,并且为这些参数提供默认值,如 <doc:Functions#Variadic-Parameters><doc:Functions#Default-Parameter-Values>中所述。但是,与函数不同的是,下标不能使用 in-out 参数。
205140

206141
<!--
207142
- test: `subscripts-can-have-default-arguments`
@@ -218,18 +153,9 @@ subscripts can't use in-out parameters.
218153
```
219154
-->
220155

221-
A class or structure can provide as many subscript implementations as it needs,
222-
and the appropriate subscript to be used will be inferred based on
223-
the types of the value or values that are contained within the subscript brackets
224-
at the point that the subscript is used.
225-
This definition of multiple subscripts is known as *subscript overloading*.
156+
一个类或结构体可以根据自身需要提供多个下标实现,使用下标时将通过入参的数量和类型进行区分,自动匹配合适的下标。它通常被称为 **下标重载**
226157

227-
While it's most common for a subscript to take a single parameter,
228-
you can also define a subscript with multiple parameters
229-
if it's appropriate for your type.
230-
The following example defines a `Matrix` structure,
231-
which represents a two-dimensional matrix of `Double` values.
232-
The `Matrix` structure's subscript takes two integer parameters:
158+
虽然下标采用单一入参是最常见的,但也可以根据情况定义接受多个入参的下标。下面的示例定义一个 `Matrix` 结构体,该结构体表示一个 `Double` 类型的二维矩阵。`Matrix` 结构体的下标接受两个整型参数:
233159

234160
```swift
235161
struct Matrix {
@@ -285,16 +211,9 @@ struct Matrix {
285211
```
286212
-->
287213

288-
`Matrix` provides an initializer that takes two parameters called `rows` and `columns`,
289-
and creates an array that's large enough to store `rows * columns` values of type `Double`.
290-
Each position in the matrix is given an initial value of `0.0`.
291-
To achieve this, the array's size, and an initial cell value of `0.0`,
292-
are passed to an array initializer that creates and initializes a new array of the correct size.
293-
This initializer is described in more detail
294-
in <doc:CollectionTypes#Creating-an-Array-with-a-Default-Value>.
214+
`Matrix` 提供了一个接受两个入参的构造方法,入参分别是 `rows``columns`,创建了一个足够容纳 `rows * columns``Double` 类型的值的数组。通过传入数组长度和初始值 `0.0` 到数组的构造器,将矩阵中每个位置的值初始化为 `0.0`。关于数组的这种构造方法请参考<doc:CollectionTypes#Creating-an-Array-with-a-Default-Value>
295215

296-
You can construct a new `Matrix` instance by passing
297-
an appropriate row and column count to its initializer:
216+
你可以通过传入合适的 `row``column` 数值来构造一个新的 `Matrix` 实例:
298217

299218
```swift
300219
var matrix = Matrix(rows: 2, columns: 2)
@@ -309,15 +228,9 @@ var matrix = Matrix(rows: 2, columns: 2)
309228
```
310229
-->
311230

312-
The example above creates a new `Matrix` instance with two rows and two columns.
313-
The `grid` array for this `Matrix` instance
314-
is effectively a flattened version of the matrix,
315-
as read from top left to bottom right:
231+
上例中创建了一个两行两列的 `Matrix` 实例。该 `Matrix` 实例的 `grid` 数组按照从左上到右下的阅读顺序将矩阵扁平化存储:
316232

317-
![](subscriptMatrix01)
318-
319-
Values in the matrix can be set by passing row and column values into the subscript,
320-
separated by a comma:
233+
`row``column` 的值传入下标来为矩阵设值,下标的入参使用逗号分隔:
321234

322235
```swift
323236
matrix[0, 1] = 1.5
@@ -337,20 +250,9 @@ matrix[1, 0] = 3.2
337250
```
338251
-->
339252

340-
These two statements call the subscript's setter to set
341-
a value of `1.5` in the top right position of the matrix
342-
(where `row` is `0` and `column` is `1`),
343-
and `3.2` in the bottom left position
344-
(where `row` is `1` and `column` is `0`):
345-
346-
![](subscriptMatrix02)
253+
上面两条语句分别调用下标的 setter 将矩阵右上角位置(即 `row``0``column``1` 的位置)的值设置为 `1.5`,将矩阵左下角位置(即 `row``1``column``0` 的位置)的值设置为 `3.2`:
347254

348-
The `Matrix` subscript's getter and setter both contain an assertion
349-
to check that the subscript's `row` and `column` values are valid.
350-
To assist with these assertions,
351-
`Matrix` includes a convenience method called `indexIsValid(row:column:)`,
352-
which checks whether the requested `row` and `column`
353-
are inside the bounds of the matrix:
255+
`Matrix` 下标的 getter 和 setter 中都含有断言,用来检查下标入参 `row``column` 的值是否有效。为了方便进行断言,`Matrix` 包含了一个名为 `indexIsValid(row:column:)` 的便利方法,用来检查入参 `row``column` 的值是否在矩阵范围内:
354256

355257
```swift
356258
func indexIsValid(row: Int, column: Int) -> Bool {
@@ -370,12 +272,11 @@ func indexIsValid(row: Int, column: Int) -> Bool {
370272
```
371273
-->
372274

373-
An assertion is triggered if you try to access a subscript
374-
that's outside of the matrix bounds:
275+
断言在下标越界时触发:
375276

376277
```swift
377278
let someValue = matrix[2, 2]
378-
// This triggers an assert, because [2, 2] is outside of the matrix bounds.
279+
// 断言将会触发,因为 [2, 2] 已经超过了 matrix 的范围
379280
```
380281

381282
<!--
@@ -388,17 +289,9 @@ let someValue = matrix[2, 2]
388289
```
389290
-->
390291

391-
## Type Subscripts
292+
## 类型下标
392293

393-
Instance subscripts, as described above,
394-
are subscripts that you call on an instance of a particular type.
395-
You can also define subscripts that are called on the type itself.
396-
This kind of subscript is called a *type subscript*.
397-
You indicate a type subscript
398-
by writing the `static` keyword before the `subscript` keyword.
399-
Classes can use the `class` keyword instead,
400-
to allow subclasses to override the superclass’s implementation of that subscript.
401-
The example below shows how you define and call a type subscript:
294+
正如上节所述,实例下标是在特定类型的一个实例上调用的下标。你也可以定义一种在这个类型自身上调用的下标。这种下标被称作 **类型下标**。你可以通过在 `subscript` 关键字之前写下 `static` 关键字的方式来表示一个类型下标。类型可以使用 `class` 关键字来代替 `static`,它允许子类重写父类中对那个下标的实现。下面的例子展示了如何定义和调用一个类型下标:
402295

403296
```swift
404297
enum Planet: Int {
@@ -428,11 +321,9 @@ print(mars)
428321
```
429322
-->
430323

431-
> Beta Software:
432-
>
433-
> This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.
434-
>
435-
> Learn more about using [Apple's beta software](https://developer.apple.com/support/beta-software/).
324+
>测试版软件:
325+
>本文档包含有关正在开发的 API 或技术的初步信息。此信息可能会发生变化,根据本文档实施的软件应使用最终操作系统软件进行测试。
326+
>了解有关使用 [Apple 测试版软件](https://developer.apple.com/support/beta-software/)的更多信息.
436327
437328
<!--
438329
This source file is part of the Swift.org open source project

0 commit comments

Comments
 (0)