Swift – Create an Array of Specific Size

To create an array of specific size in Swift, use Array initialiser syntax and pass this specific size. We also need to pass the default value for these elements in the Array.

The syntax of Array initialiser to create an array of specific Size, and with a default value is

Array(repeating: defaultValue, count: specificSize)

The following code snippet returns an Array of size 4 with default value of 0. The datatype of this array is inferred from the repeating value, which is the default value.

var myArray = Array(repeating: 0, count: 4)

Example

In this example, we will create a String Array of size 8. To use Array initialiser syntax, we need to specify repeating or default value, and the count. We have the count 8. And for repeating, let us take "", since we would like to create a String Array.

main.swift

var myArray = Array(repeating: "", count: 8)
print(myArray)

Output

["", "", "", "", "", "", "", ""]

Conclusion

In this Swift Tutorial, we learned how to create an Array of specific size using Array initialiser syntax.