Swift – Create an Empty Array
To create an empty array in Swift, use initialiser syntax.
The following code snippet creates an empty Int array.
var myIntArray = [Int]()
The type of elements we would like store in the array is provided in square brackets. And parenthesis after this datatype declaration would initialise the empty array of this type.
Now, we can add only Integer elements to this Array, since myIntArray is declared that it would store Int elements only.
Similarly, we can create empty arrays of any specific datatype.
The following code snippet creates an empty Double array.
var myArray = [Double]()
The following code snippet creates an empty Float array.
var myArray = [Float]()
The following code snippet creates an empty String array.
var myArray = [String]()
Example
Let us create an empty array that would store Int values. And also append some Int values.
main.swift
var myIntArray = [Int]()
myIntArray.append(41)
myIntArray.append(22)
print(myIntArray)
Output
[41, 22]
If we try to add elements of other type, then the build would fail.
For example, let us try to add elements of another type.
main.swift
var myIntArray = [Int]()
myIntArray.append(41)
myIntArray.append("Hello")
print(myIntArray)
Output
Cannot convert value of type 'String' to expected argument type 'Int'
Conclusion
In this Swift Tutorial, we learned how to create an Empty array of specific type, and how to get started to work on these empty arrays.