Initialize array with specific size in Swift
This tutorial has information related to the initialization of an array with a specific size in Swift. Whenever there is a need to initialize an array of specific size, we can use this method.
Array initializer method:
We can use Array initializer method which takes two parameters namely
count. The repeating means to insert a default value and
count takes the size as parameter.
Array(repeating: Value, count: Size)
For example, we need to create an array of value 0 and size 6. So the syntax would be-
Array(repeating: 0, count:6)
We have three methods through which we can declare the array of a specific size-
- Declaring an empty Array.
- Array with a default value and specific size.
- Array with some initializing values.
Declare an empty array
Sometimes we need to create an empty array to work on and then append some values. To declare an empty array we just need to code as below-
var nullarray = [Int]() print(nullarray)
This creates an empty array of 0 elements.
We can implement this for strings too in the same way.
Array with a default value and fixed size
As we have discussed about the syntax in the above paragraph we now need to implement it with a particular value and the size we need. We can easily proceed further with the below snippet-
var myArray = Array(repeating: 0, count: 8) print(myArray)
Output-[0, 0, 0, 0, 0, 0, 0, 0]
As discussed above whenever we need an array of similar elements of a particular size, we can implement this method.
Again we can use this method for string as well.
Array with some initializing values
We use this method very often, like when we know the values and we need to create an array of fixed elements, we can simply use this method as-
var myArray=[1,2,3,4] print(myarray)
Output-[1, 2, 3, 4]
We have created an array of the above-mentioned elements as initialization values. Also, this can be used for strings as well.
This tutorial has taught us three different ways to initialize the array in Swift. Firstly we declared the empty array with no elements, then there is an array of similar elements and lastly an array with some initializing values.