I have a large array in Swift. I want to initialize all members to the same value (i.e. it could be zero or some other value). What would be the best approach?
Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.
There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.
To initialize a set with predefined list of unique elements, Swift allows to use the array literal for sets. The initial elements are comma separated and enclosed in square brackets: [element1, element2, ..., elementN] .
To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.
Actually, it's quite simple with Swift. As mentioned in the Apple's doc, you can initialize an array with the same repeated value like this:
With old Swift version:
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
Since Swift 3.0:
var threeDoubles = [Double](repeating: 0.0, count: 3)
which would give:
[0.0, 0.0, 0.0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With