Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize all members of an array to the same value in Swift?

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?

like image 614
m_power Avatar asked Jun 02 '14 19:06

m_power


People also ask

How do you initialize all members of an array to the same value?

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.

How do you initialize an array with all elements?

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.

How do I initialize an array in Swift?

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] .

How do you initialize an array with values?

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.


1 Answers

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] 
like image 190
moumoute6919 Avatar answered Sep 26 '22 06:09

moumoute6919