Skip to content

Commit 808839a

Browse files
authored
Fix type inference example in "Creating an Empty Array" (#341)
The existing prose and code listing didn't match -- the prose discussed type inference, but the code listing used an explicit type annotation.
2 parents e0493a4 + 7d77240 commit 808839a

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

TSPL.docc/LanguageGuide/CollectionTypes.md

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,12 @@ and is used throughout this guide when referring to the type of an array.
7070

7171
### Creating an Empty Array
7272

73-
You can create an empty array of a certain type
74-
using initializer syntax:
73+
You can create an empty array in Swift using two approaches.
74+
If the context already provides type information,
75+
such as a function argument or an already typed variable or constant,
76+
you can use an empty array literal,
77+
which is written as `[]`
78+
(an empty pair of square brackets):
7579

7680
```swift
7781
var someInts: [Int] = []
@@ -89,14 +93,24 @@ print("someInts is of type [Int] with \(someInts.count) items.")
8993
```
9094
-->
9195

92-
Note that the type of the `someInts` variable is inferred to be `[Int]`
93-
from the type of the initializer.
96+
Alternatively, you can create an empty array of a certain type
97+
using explicit initializer syntax,
98+
by writing the element type in square brackets
99+
followed by parentheses ---
100+
for example, `[Int]()` in the following:
94101

95-
Alternatively, if the context already provides type information,
96-
such as a function argument or an already typed variable or constant,
97-
you can create an empty array with an empty array literal,
98-
which is written as `[]`
99-
(an empty pair of square brackets):
102+
```swift
103+
var someInts = [Int]()
104+
print("someInts is of type [Int] with \(someInts.count) items.")
105+
// Prints "someInts is of type [Int] with 0 items."
106+
```
107+
108+
Both approaches produce the same result.
109+
However,
110+
an empty array literal is shorter and usually easier to read.
111+
112+
In both cases, you can use the empty array literal (`[]`) to
113+
reassign an empty array to an existing variable:
100114

101115
```swift
102116
someInts.append(3)

0 commit comments

Comments
 (0)