In Swift, an array is an ordered collection of values. These values can be of any type: integers, strings, dictionaries, and even custom types.
In this tutorial, you will learn how to create an empty Array in Swift.
If you are interested in video lessons then check my video course Apache Kafka for Event-Driven Spring Boot Microservices.
Empty Array of Integers
To create an empty array of integers, you can use the following syntax:
var intArray = [Int]()
This line of code declares a mutable variable intArray
of type [Int]
(an array of integers) and initializes it as an empty array.
Empty Array of String type
Similarly, to create an empty array of strings, you can use the following syntax:
var stringArray = [String]()
Above, you declare a mutable variable stringArray
of type [String]
(an array of strings) and initializes it as an empty array.
Empty Array of Dictionary type
Creating an empty array of dictionaries involves specifying the types of keys and values. For instance, if you want to create an empty array of dictionaries with String
keys and Int
values, you can use the following syntax:
var dictArray = [[String: Int]]()
Same as before you declare a mutable variable dictArray
of type [[String: Int]]
(an array of dictionaries with String
keys and Int
values) and initializes it as an empty array.
After declaring it, you can check if an array is empty or not.
Empty Array of Additional Types
You can also create empty arrays of other types, such as floating-point numbers (Float
or Double
), booleans (Bool
), and even custom types. The process is similar to the ones described above.
For example, to create an empty array of Double
:
var doubleArray = [Double]()
Or an empty array of Bool
:
var boolArray = [Bool]()
Remember, the type of the array is determined by the type of elements you plan to store in it. Once you’ve created an empty array, you can add elements to it.
Conclusion
I hope this tutorial was helpful you. To learn more about Arrays in Swift, check out the tutorial on Create an Array with Default Values in Swift.
To learn more about Swift and find other code examples, please check the Swift Code Examples page on this website.
If you are interested in video lessons then check my video course Apache Kafka for Event-Driven Spring Boot Microservices.