How to create arrays in Swift?

Prerequisites

Please make sure you watch first the following prerequisite videos:

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

We learned last time that arrays are un-keyed, multi-value collections of elements, all under a single name. And we learned to access individual elements by using an index, which indicates the position of the element in the array. But when we don’t already have an array to work with, how do we create one?

We start with a pair of square brackets. Inside these brackets we write the elements of the array, separated by commas. What we have now is an expression of type array. And this expression can be assigned to a variable or a constant. Please note that all elements in an array need to have the same data type. Well, except when they don’t, we will discuss that in another video.

This is an array of integers. We didn’t declare it as such, but we can, if we want to. Colon declares the type, and Int between a pair of square brackets means the type is array of integers.

However, declaring the type is not necessary in this case, because the compiler can infer the type by itself.

This is an array of Strings. Same thing: a sequence of elements (this time String elements) inside square brackets. And hey, don’t forget the commas.

We could be more specific and declare the type, but it’s really not needed. The compiler takes care of that for us.

And there you have it. Creating new arrays is as easy as writing a sequence of array elements, separated by commas, inside a pair of square brackets. This generates an array expression, which can be assigned to a variable or a constant. And because of the compiler’s ability to infer type, in most cases we don’t even need to declare the type.