Swift – Create an Array with Default Value
To create an array with default value in Swift, use Array initialiser syntax and pass this default value. We also need to pass the size of the Array for the Array initialiser.
The syntax of Array initialiser to create an array with specific 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 with default value of "abc"
. So repeating
in the Array initialiser would be "abc"
. To use Array initialiser syntax, we need to pass count
as well. Let us give a value of 8
for the count
.
main.swift
var myArray = Array(repeating: "abc", count: 8)
print(myArray)
Output
["abc", "abc", "abc", "abc", "abc", "abc", "abc", "abc"]
Conclusion
In this Swift Tutorial, we learned how to create an Array with specific default value using Array initialiser syntax.