'Creating a limited count array of custom type

I am creating array of Promises of type [MSGraphScheduleInformation?]. I want to limit the array count to 4, but the repeating param in the API is throwing errors. Below is my code:

For infinite array count the code looks like this:

var array = [Promise<[MSGraphScheduleInformation?]>] // This works

For array with limited count:

var array = [Promise<[MSGraphScheduleInformation?]>](repeating: Promise<[MSGraphScheduleInformation?]>, count: 4) // Throws error

Error I get with above line is - Cannot convert value of type 'Promise<[MSGraphScheduleInformation?]>.Type' to expected argument type 'Promise<[MSGraphScheduleInformation?]>'

Here is what I want eventually:

[Promise<[MSGraphScheduleInformation?] Object 1, 
 Promise<[MSGraphScheduleInformation?] Object 2, 
 Promise<[MSGraphScheduleInformation?] Object 3, 
 Promise<[MSGraphScheduleInformation?] Object 4]

How do I create an array with count and custom type?



Solution 1:[1]

As the error message says, you are passing a Type when an instance of that Type is expected.

The repeating initialiser of Array places the value specified by the repeating parameter into the first count indices of the array.

It does not, as your question implies you think, create an array whose elements are the type specified by the repeating array and is limited in size to count.

You should also note that repeating does not specify an initialiser to be called for each element. It is literally the item that will be placed in each index.

You could say something like

var array = [Promise<[MSGraphScheduleInformation?]>](repeating: Promise<[MSGraphScheduleInformation?]()>, count: 4)

You are now passing an instance of a Promise, but you will end up, with that same instance in the first 4 indices. :


[Promise<[MSGraphScheduleInformation?] Object 1, 
 Promise<[MSGraphScheduleInformation?] Object 1, 
 Promise<[MSGraphScheduleInformation?] Object 1, 
 Promise<[MSGraphScheduleInformation?] Object 1]

(I am ignoring whether Promise<[MSGraphScheduleInformation?]()> is even a valid initialiser).

Finally, count only specifies the initial size of the array. It isn't an upper or lower limit that somehow applies to the life of the array. You can remove and append items just like any array.

If you want to limit the number of items in the array you need to do that in your code.

If you want to pre-populate 4 promises, you can use a simple for loop, but that doesn't make a lot of sense. I don't see how you can create a promise before you know what it is promising; I.E. how the promise will be fulfilled.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paulw11