Mattkx4
Mattkx4

Reputation: 309

How to Define an Optional Array with a Fixed Size [Swift 3]

I'm trying to define an array of objects. The array needs to have 3 spaces. At the variable initialization, they're set to nil, but later on in the program, they're filled in (they're filled in before they're used).

Here's what I have so far:

var scrollLayers: [SKNode?]! = [nil, nil, nil]

And this works fine, but if I have, for example, 50 spots that need to be initialized, I don't want to have to type "nil, " 50 times. Is there a way to make this array 50 spots big and have all those spots set to nil?

Thanks, Matthew

Upvotes: 0

Views: 6141

Answers (2)

tetsuo
tetsuo

Reputation: 61

For those that prefer this syntax:

var scrollLayers: [SKNode?] = Array(repeating: nil, count: 50)

Upvotes: 1

nshoute
nshoute

Reputation: 237

var scrollLayers = [SKNode?](repeating: nil, count: 50)

Upvotes: 9

Related Questions