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
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…