Skip to content

Commit 21215ce

Browse files
Improve "Creating an Empty Array" section in Language Guide
- Highlight empty array literals (`[]`) as the preferred method. - Add initializer syntax (`[Type]()`) as an alternative. - Reorganize examples to reduce redundancy and improve clarity.
1 parent cca0641 commit 21215ce

File tree

1 file changed

+34
-9
lines changed

1 file changed

+34
-9
lines changed

TSPL.docc/LanguageGuide/CollectionTypes.md

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,34 @@ 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 one of two approaches:
74+
75+
If the context already provides type information,
76+
such as a function argument or an already typed variable or constant,
77+
you can create an empty array with an *empty array literal*,
78+
which is written as `[]`
79+
(an empty pair of square brackets):
80+
81+
```swift
82+
var someInts: [Int] = []
83+
print("someInts is of type [Int] with \(someInts.count) items.")
84+
// Prints "someInts is of type [Int] with 0 items."
85+
```
86+
87+
<!--
88+
- test: `arraysEmpty`
89+
90+
```swifttest
91+
-> var someInts: [Int] = []
92+
-> print("someInts is of type [Int] with \(someInts.count) items.")
93+
<- someInts is of type [Int] with 0 items.
94+
```
95+
-->
96+
97+
Alternatively, you can create an empty array of a certain type
98+
using *initializer syntax*,
99+
which is done by writing the type in square brackets
100+
followed by parentheses (`[Element]()`):
75101

76102
```swift
77103
var someInts = [Int]()
@@ -89,14 +115,13 @@ print("someInts is of type [Int] with \(someInts.count) items.")
89115
```
90116
-->
91117

92-
Note that the type of the `someInts` variable is inferred to be `[Int]`
93-
from the type of the initializer.
118+
Both approaches produce the same result.
119+
However, the empty array literal (`[]`) is the preferred way to
120+
initialize an empty array because it is more concise and aligns with
121+
the style guidelines used throughout this guide.
94122

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):
123+
In both cases, you can use the empty array literal (`[]`) to
124+
reassign an empty array to an existing variable:
100125

101126
```swift
102127
someInts.append(3)

0 commit comments

Comments
 (0)