How to create an empty array in Swift
In this tutorial, we will learn how to create an empty array in Swift.
We will show you one by one the followings:
- Create an empty Int array in Swift
- Create an empty String array
The basic syntax for creating an empty array is as follows:
var myArrayName = [Data_type] ()or
let myArrayName = [Data_type] ()
var myArrayName: [Data_type] = or
let myArrayName: [Data_type] = 
You can also read: Get random element from an array in Swift
Create an empty Int array
We can create Int type of array with no values in it using the below line of code
var emptyArray : [Int] = 
or we can also use the below:
let emptyArray = [Int] ()
or you can also do this:
var emptyArray: [Int] = 
Create an empty String array
Here again, we will proceed with the same method mentioned above. Just we need to change the data type here. Just look at the code below.
var emptyArray: [String] = 
var emptyArray = [String] ()
or you can use
let instead of
var as per your requirement.
What will happen if you don’t declare any data type to your array?
var emptyArray =  if you run this you will be getting an error like this: “Empty collection literal requires an explicit type“
This means in case of empty array creation in Swift, you must have to set the data type.
But if you add an item in your array at the time of array creation then it is not mandatory to set the data type. Swift will automatically detect the type of your array just like below:
var emptyArray = ["Macbook"] print(emptyArray)