如何创建固定大小的对象数组 [英] How to create a fixed-size array of objects

查看:544
本文介绍了如何创建固定大小的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,我正在尝试创建一个包含64个SKSpriteNode的数组。我想先将它初始化为空,然后我将精灵放在前16个单元格中,最后16个单元格(模拟国际象棋游戏)。

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];

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.

推荐答案

目前还不支持定长数组。这究竟意味着什么?并不是说你不能创建一个 n 的数组 - 显然你可以做让a = [1,2,3] 获取三个 Int 的数组。这意味着只是数组大小不能将声明为类型信息

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 Ints. It means simply that array size is not something that you can declare as type information.

如果你想要一个 nil s,你首先需要一个可选类型的数组 - [SKSpriteNode?] ,而不是 [SKSpriteNode ] - 如果声明一个非可选类型的变量,无论是数组还是单个值,它都不能是 nil 。 (还要注意 [SKSpriteNode?] [SKSpriteNode]不同? ...你想要一个选项数组,而不是一个可选的数组。)

If you want an array of nils, 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在设计上非常明确地要求对变量进行初始化,因为关于未初始化引用内容的假设是程序的一种方式在C(和其他一些语言)可以成为越野车。所以,你需要明确要求一个 [SKSpriteNode?] 数组,其中包含64 nil s:

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 nils:

var sprites = [SKSpriteNode?](repeating: nil, count: 64)

这实际上返回 [SKSpriteNode?]?,但是:可选的sprite数组。 (有点奇怪,因为 init(count:,repeatedValue:)不应该返回nil。)要使用数组,你需要打开它。有几种方法可以做到这一点,但在这种情况下,我更喜欢可选的绑定语法:

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
}

这篇关于如何创建固定大小的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆