0

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

3
  • 1
    Yet another documentation fail. "If you need an array that is preinitialized with a fixed number of default values..." It doesn't get any plainer. Commented Dec 4, 2016 at 3:16
  • @matt Thanks for the link to the docs! If I'm going to be honest with you, I didn't even know this documentation existed. I'm super new to Swift programming despite, and several google searches, I couldn't figure it out. Thanks again :) Commented Dec 4, 2016 at 4:41
  • That documentation is on your computer. Commented Dec 4, 2016 at 15:58

2 Answers 2

9
var scrollLayers = [SKNode?](repeating: nil, count: 50)
Sign up to request clarification or add additional context in comments.

2 Comments

any option for non-optional values?
You can't initialize a non-optional array with optionals, but you can do this: var threeDoubles = [Double](repeating: 0.0, count: 3)
1

For those that prefer this syntax:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.