@@ -70,8 +70,34 @@ and is used throughout this guide when referring to the type of an array.
70
70
71
71
### Creating an Empty Array
72
72
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]() ` ):
75
101
76
102
``` swift
77
103
var someInts = [Int ]()
@@ -89,14 +115,13 @@ print("someInts is of type [Int] with \(someInts.count) items.")
89
115
```
90
116
-->
91
117
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.
94
122
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:
100
125
101
126
``` swift
102
127
someInts.append (3 )
0 commit comments