如何定义具有固定大小的可选数组[Swift 3]

时间:2023-02-06 21:45:08

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

我正在尝试定义一个对象数组。该阵列需要有3个空格。在变量初始化时,它们被设置为nil,但是稍后在程序中,它们被填充(它们在被使用之前被填充)。

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?

这样工作正常,但如果我有50个需要初始化的点,我不想输入“nil”50次。有没有办法让这个数组50个点大,并将所有这些点设置为零?

Thanks, Matthew

谢谢,马修

2 个解决方案

#1


9  

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

#2


0  

For those that prefer this syntax:

对于那些喜欢这种语法的人:

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

#1


9  

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

#2


0  

For those that prefer this syntax:

对于那些喜欢这种语法的人:

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