How to create EMPTY arrays in Swift?

So how to create empty arrays in Swift? Let’s discuss…

We learned last time that we can create arrays by enclosing a bunch of elements inside a pair of square brackets. These elements will be separated by commas.

This is an array of integers, that can be assigned to a variable or constant, if we wish. And this is an array of strings, assigned to a constant called cities.

Now, an array of a custom structure of our own, let’s call it Person, would look like this. It is an array of Person.

In each case, we did not explicitly declare the type of the array, because the compiler can infer it. But, when we want to create an empty array, there is not enough context for inference. We have to explicitly declare the array’s type when we create an empty one, by enclosing a data type in square brackets before assigning the value of an empty array.

The order matters: first, the type declaration (with a colon), and second, assigning an empty array, with an equal sign.

There are a few other ways to do the same thing. My favorite is using the initializer (which means empty rounded parentheses) after a type declaration, like an array of integers, for example.

Another way is to use the array’s data type name, which is the actual word Array used instead of a pair of square brackets. In this case, however, the type of the array’s elements needs to be indicated using the generics syntax, a pair of angle brackets.

And there you have it. Creating empty arrays can be done in a variety of different ways, but in all cases the type of the array (deducted from the type of its elements) needs to be declared explicitly. When we start with an empty array, there is no way for the compiler to infer the array’s type.