In Swift, I am trying to create an array of 64 SKSpriteNode. I want first to initialize it empty, then I would put Sprites in the first 16 cells, and the last 16 cells (simulating an chess game).
From what I understood in the doc, I would have expect something like:
var sprites = SKSpriteNode()[64];
or
var sprites4 : SKSpriteNode[64];
But it doesn't work. In the second case, I get an error saying: "Fixed-length arrays are not yet supported". Can that be real? To me that sounds like a basic feature. I need to access the element directly by their index.
Fixed-length arrays are not yet supported. What does that actually mean? Not that you can't create an array of n
many things — obviously you can just do let a = [ 1, 2, 3 ]
to get an array of three Int
s. It means simply that array size is not something that you can declare as type information.
If you want an array of nil
s, you'll first need an array of an optional type — [SKSpriteNode?]
, not [SKSpriteNode]
— if you declare a variable of non-optional type, whether it's an array or a single value, it cannot be nil
. (Also note that [SKSpriteNode?]
is different from [SKSpriteNode]?
... you want an array of optionals, not an optional array.)
Swift is very explicit by design about requiring that variables be initialized, because assumptions about the content of uninitialized references are one of the ways that programs in C (and some other languages) can become buggy. So, you need to explicitly ask for an [SKSpriteNode?]
array that contains 64 nil
s:
var sprites = [SKSpriteNode?](repeating: nil, count: 64)
This actually returns a [SKSpriteNode?]?
, though: an optional array of optional sprites. (A bit odd, since init(count:,repeatedValue:)
shouldn't be able to return nil.) To work with the array, you'll need to unwrap it. There's a few ways to do that, but in this case I'd favor optional binding syntax:
if var sprites = [SKSpriteNode?](repeating: nil, count: 64){
sprites[0] = pawnSprite
}